简体   繁体   English

Codeigniter - 活动记录 - sql - 复杂连接

[英]Codeigniter - Active record - sql - complex join

I have a function that retrieves all tags from a table: 我有一个从表中检索所有标签的函数:

function global_popular_tags() {
    $this->db->select('tags.*, COUNT(tags.id) AS count');
    $this->db->from('tags');
    $this->db->join('tags_to_work', 'tags.id = tags_to_work.tag_id');
    $this->db->group_by('tags.id');
    $this->db->order_by('count', 'desc'); 
    $query = $this->db->get()->result_array();
    return $query;
}

I have another table called 'work'. 我有另一张名为'work'的表。 The 'work' table has a 'draft' column with values of either 1 or 0. I want the COUNT(tags.id) to take into account whether the work with the specific tag is in draft mode (1) or not. 'work'表有一个'draft'列,其值为1或0.我希望COUNT(tags.id)考虑具有特定标记的工作是否处于草稿模式(1)。

Say there are 10 pieces of work tagged with, for example, 'design'. 比如,有10件作品被标记为“设计”。 The COUNT will be 10. But 2 of these pieces of work are in draft mode, so the COUNT should really be 8. How do I manage this? COUNT将是10.但是这些工作中有2个处于草稿模式,因此COUNT应该是8.如何管理?

Try changing: 尝试改变:

$this->db->from('tags');
$this->db->join('tags_to_work', 'tags.id = tags_to_work.tag_id');

To: 至:

$this->db->from('tags, work');
$this->db->join('tags_to_work', 'tags.id=tags_to_work.tag_id AND work.id=tags_to_work.work_id');

And Adding: 并添加:

$this->db->where('work.drafts', 0);

You can use pure sql instead of using the active record class, I myself are working with CI for over 2 years and most of the time I am avoiding the active record class, cause straight sql is much easier to debug and write complex queries. 您可以使用纯sql而不是使用活动记录类,我自己正在使用CI超过2年,并且大部分时间我避免使用活动记录类,导致直接sql更容易调试和编写复杂查询。 This is how i would use it. 这就是我如何使用它。

$sql = "SELECT...your sql here";
$q = $this->db->query($sql);
...
//Do something with your query here

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

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