2017-07-01 97 views
0

我有三個表:用戶類別users_cateogires笨多對多查詢

我需要爲特定用戶獲得用戶所有用戶表和他擁有的類別的名稱。在簡單的mySql我會做這樣的事情:

select u.*, 
(select GROUP_CONCAT(name) from projects as p where p.user_id = u.id_user) as projects, 
(select GROUP_CONCAT(name) from categories as c where c.id_cat in 
(select cat_id from users_categories where user_id = u.id_user)) 
as categories from users as u 

但我找不到使用codeigniter的活動記錄類的結果的方式。

+0

您使用的活動記錄想查詢。是嗎? –

+0

是的!那就對了。 –

+0

你爲什麼不去加入? –

回答

0
$this->db->select('GROUP_CONCAT(name)'); 
    $this->db->from('projects p'); 
    $this->db->where('p.user_id', 'u.id_user'); 
    $first_clause = $this->db->get_compiled_select(); 

    $this->db->select('cat_id'); 
    $this->db->from('users_categories'); 
    $this->db->where('user_id', 'u.id_user'); 
    $second_clause = $this->db->get_compiled_select(); 

    $this->db->select('GROUP_CONCAT(name)'); 
    $this->db->from('categories as c'); 
    $this->db->where("c.id_cat in ($second_clause) as u", NULL, FALSE); 
    $third_clause = $this->db->get_compiled_select(); 


    $this->db->select('u.*,$first_clause,$third_clause'); 
    $this->db->from('users as u'); 
    $query = $this->db->get(); 
    $result = $query->row_array(); 
    if ($query->num_rows() > 0) { 
     return $result; 
    } else { 
     return null; 
    } 

編譯語句就是你要找的。現在這可能是一種快速和骯髒的方式,並且可能有更好的方法,但是如果你在截止日期之前,這應該能夠完成工作。

我發送的查詢不是很好地檢查,它只是將您推向正確的方向。

1

你也可以在模型

直接使用SQL這樣的查詢

$sql = "select u.*, (select GROUP_CONCAT(name) from projects as p where p.user_id = u.id_user) as projects, (select GROUP_CONCAT(name) from categories as c where c.id_cat in (select cat_id from users_categories where user_id = u.id_user)) as categories from users as u"; 
$query = $this->db->query($sql); 
$result = $query->result_array();