繁体   English   中英

Codeigniter多对多查询

[英]Codeigniter Many to Many query

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

您也可以直接在模型中使用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();
    $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;
    }

您正在寻找已编译的语句。 现在,这可能是一种快速而肮脏的方法,并且可能还有一种更好的方法,但是如果您按时完成任务,则应该可以完成工作。

我发送的查询并没有得到很好的检查,它只是将您推向正确的方向。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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