Codeigniter多对多查询

时间:2017-07-01 18:25:27

标签: php mysql codeigniter many-to-many

我有三个表:用户类别 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的Active Record类来获得此结果的方法。

2 个答案:

答案 0 :(得分:1)

您也可以直接在Model

中使用SQL Query

喜欢这个

String MyVar = {{4,3,1},{6,4,1},{7,3,1},{7,6,1},{6,7.5,1},{3,6,1},{4,5,2},{5,6.5,2},{6,9,2},{3.5,8,2},{6,5,3},{6,6,3},{9,4,3},{9,5,3},{8,4,4},{9.5,3,4},{10,4,4},{11,6,4},{9,6,4},{8,7,5},{10,7,5},{11,9,5},{8,10,5}} ;

double MyPoints [25][3] = MyVar ;
cout << "Array Filled" << endl;

答案 1 :(得分: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;
    }

编译语句是您正在寻找的。现在这可能是一种快速而肮脏的方式,并且可能有更好的方法,但是如果你在截止日期之前就应该完成工作。

我发送的查询并没有得到很好的检查,只是为了让你朝着正确的方向前进。