简体   繁体   中英

Join 3 mysql tables php codeigniter

I have below type of 3 tables, where finally I need to get shop_admin and shop_coadmin email address which are part of users table.

table-1-shop
-------------------------------
shop_id | shop_name | shop_admin(foreignkey user_id) | shop_coadmin(foreignkey user_id)

table-2-Users
-------------------------------
user_id |  user_name |  user_email

table-3-orders
--------------------------------
order_id | shop_id    

Now my requirement is to get shop_admin and shop_coadmin email ids from users table,

Orders contains shop_id , and with shop_id it will search admin and coadmin id s, and with that it need to search in users for user_email ,

I tried below code but i could not get emails

public function getAllCart($user_id,$paging, $ordering, $searching )
{
    $this->db->select('part_number, part_description, order_quantity, order_id, B.user_firstname, B.user_lastname, B.user_email, A.shop_name,
     A.shop_admin AS shop_admin');
    $this->db->from('li_orders');
    $paging;
    $ordering;
    $searching;

    $this->db->where('order_status', 'Cart');
    $this->db->join('li_parts', 'li_parts.part_id = li_orders.part_id','LEFT');
    $this->db->join('li_shop AS A', 'A.shop_id = li_orders.shop_id','LEFT');
    $this->db->join('li_users AS B', 'B.user_id = A.shop_admin','LEFT');
    $this->db->where('li_orders.user_id', $user_id);
    return $this->db->get()->result_array();
}

How can I get that?

If your problem is that you only get shop_admin's email with the above code, then you need to add the li_users table with another alias to the query and join it on li_shop.coadmin field. Obviously, you need to add the fields from the table with the new alias and mark which user details are for the admin and which are for the coadmin using field aliases.

...
$this->db->select('part_number, part_description, order_quantity, order_id, B.user_firstname as adminfirstname, B.user_lastname as adminlastname, B.user_email as adminemail, C.user_firstname as coadminfirstname, C.user_lastname as coadminlastname, C.user_email as coadminemail, A.shop_name,
 A.shop_admin AS shop_admin');
...
$this->db->join('li_users AS B', 'B.user_id = A.shop_admin','LEFT');
$this->db->join('li_users AS C', 'C.user_id = A.shop_coadmin','LEFT');
...

Next time pls use the same table and field names when you describe the table structures as used in the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM