Codeigniter中的嵌套连接

时间:2017-03-01 14:48:25

标签: php mysql codeigniter activerecord

如何在Codeigniter框架中运行此SQL查询?

SELECT  users.*,
  GROUP_CONCAT(category.title SEPARATOR ',') as title 
  FROM users 
  LEFT JOIN (
    procducts as pr 
    INNER JOIN category ON pr.category_id =category.id
  ) 
  ON (users.id=pr.user_id)   
GROUP BY users.id

在Codeigniter中使用Active Record(查询构建器类)而不使用db->query

2 个答案:

答案 0 :(得分:0)

Codeigniter文档explain a join如下:

join($table, $cond[, $type = ''[, $escape = NULL]])

没有关于嵌套连接支持的文档。因此,您可以创建一个类似的查询:

$this->db->select('users.*, GROUP_CONCAT(category.title SEPARATOR ',') as title')
         ->from('users')
         ->join('procducts as pr INNER JOIN category ON pr.category_id =category.id','users.id=pr.user_id','left')
         ->group_by('users.id');
$query = $this->db->get();

答案 1 :(得分:0)

我使用此代码

$this->db->select("
              users.*,GROUP_CONCAT(category.title SEPARATOR ',')            
              as title FROM users LEFT JOIN 
                        (procducts as pr INNER JOIN category ON                          
                             pr.category_id =category.id) 
                        ON (users.id=pr.user_id)");


$this->db->group_by("users.id");

这个代码没问题,没有任何问题。