codeigniter active record left join

后端 未结 2 935
旧巷少年郎
旧巷少年郎 2021-01-03 20:28

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 exp

2条回答
  •  我在风中等你
    2021-01-03 20:42

    @m khalid 's answer is correct but I have created a dynamic function to achieve join with multiple tables. Check this out.

    function join_records($table, $joins, $where = false, $select = '*', $orderBy = false, $direction = 'DESC'){
      $CI->select($select);
      $CI->from($table);
      foreach($joins as $join){
        $CI->join($join[0], $join[1], $join[2]);
      }
      if($where) $CI->where($where);
      if($orderBy) $CI->order_by($orderBy, $direction);
      $query = $CI->get();
      return $query->result_array();
    }
    


    Applying your question to this.

    $table = 'emails';
    
    $joins[0][0] = 'user_email';
    $joins[0][1] = 'user_email.user_id = emails.id';
    $joins[0][2] = 'left';
    
    $where['user_id'] = $userid;
    

    You may add more join like $join1[0].. If you need to select some specific column you can define in following manner $select = 'table1.column1, table1.column2, table2.column1, table2.column2' Or if you want all the columns put a *

    $this->join_records($table, $joins, $where, $select);
    

    You may also find it here.

提交回复
热议问题