Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/251.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Codeigniter正确加入请求_Php_Mysql_Codeigniter_Activerecord - Fatal编程技术网

Php Codeigniter正确加入请求

Php Codeigniter正确加入请求,php,mysql,codeigniter,activerecord,Php,Mysql,Codeigniter,Activerecord,我有两个表,其中包含下一个结构和数据: 表1-事件: id name about owner_id 1 Event1 <description> 2 2 Event2 <description> 1 3 Event3 <description> 2 4 Event4 <description> 2 我需要获取当前用户(即id为2的用户)的所有事件,并加入此事件的关注者计数。现在我使用以下代

我有两个表,其中包含下一个结构和数据:

表1-事件:

id  name    about          owner_id
1   Event1  <description>  2
2   Event2  <description>  1
3   Event3  <description>  2
4   Event4  <description>  2
我需要获取当前用户(即id为2的用户)的所有事件,并加入此事件的关注者计数。现在我使用以下代码:

    $this->db->select('events.*, COUNT(event_follows.id) as followers')
            ->from('events')
            ->where('events.owner_id', $id); // $id - equals 2

    $this->db->join('event_follows', 'event_follows.event_id = events.id', 'left')
            ->group_by('event_follows.event_id');
一切似乎都很好,但有一个问题。此代码仅返回3个事件中的2个-id为1和4的事件。据我所知,这是因为事件3没有追随者


那么,如何正确地获取所有事件并获取其追随者的数量,包括那些拥有0追随者的事件?

为了从
事件
表中获取所有行,您需要按
事件.id
分组,而不是按照
事件。事件id

$this->db->select('events.*, COUNT(event_follows.id) as followers')
        ->from('events')
        ->where('events.user_id', $id); // $id - equals 2

$this->db->join('event_follows', 'event_follows.event_id = events.id', 'left')
        ->group_by('events.id'); //change to events.id

即使有多个event_follows条目用于这些event_ID,您是否仍能获得事件1和2的有效结果?我希望group_by始终返回值1
$this->db->select('events.*, COUNT(event_follows.id) as followers')
        ->from('events')
        ->where('events.user_id', $id); // $id - equals 2

$this->db->join('event_follows', 'event_follows.event_id = events.id', 'left')
        ->group_by('events.id'); //change to events.id