Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

codeigniter active record left join

I have 3 mysql tables.

Table 1 user   id | name    Table 2 emails   id | email    Table 3 user_email   user_id | email_id   

I have no experience in query multi tables.
Using codeigniter active record, i want to find out the user email address based on the user id, pls advise if the below code is correct ?

$CI->db->select('email'); $CI->db->from('emails'); $CI->db->where('id', $userid); $CI->db->join('user_email', 'user_email.user_id = emails.id', 'left'); $query = $CI->db->get();   
like image 973
user1884324 Avatar asked May 06 '14 05:05

user1884324


People also ask

How add left join in CodeIgniter?

If you want to use left outer join OR left join, pass the third parameter in join() function/method using Codeigniter. $this->db->select('*') ->from('users') ->join('comments','comments. user_id = users. u_id','left')//this is the left join in codeigniter ->get();

What is active record CodeIgniter?

Active Record Class CodeIgniter uses a modified version of the Active Record Database Pattern. This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting. In some cases only one or two lines of code are necessary to perform a database action.

How use distinct in join query in CodeIgniter?

You can use below mentioned query. $query = $this->db->group_by('category_master. Category_Id,business_profile_details. Business_Id');


1 Answers

You have wrong where clause you need to compare user_id from your table ,you are comparing the id of email to the provided $user_id

$CI->db->select('email'); $CI->db->from('emails'); $CI->db->where('user_id', $userid); $CI->db->join('user_email', 'user_email.user_id = emails.id', 'left'); $query = $CI->db->get();  

A more useful way is to give aliases to your tables so the tables with same columns will not have any confusion

$CI->db->select('e.email'); $CI->db->from('emails e'); $CI->db->join('user_email ue', 'ue.user_id = e.id', 'left'); $CI->db->where('ue.user_id', $userid); $query = $CI->db->get();  
like image 192
M Khalid Junaid Avatar answered Sep 30 '22 06:09

M Khalid Junaid