如何在Codeigniter查询中使用联接表计算总评论和总点赞次数

时间:2018-12-27 08:00:01

标签: php mysql codeigniter

我正在尝试将所有帖子发布到我的社交媒体数据库中。

它检索发布的所有用户信息,评论和喜欢的列表。

现在,我已经成功检索了每个帖子的总评论,但无法计算每个帖子的所有喜欢次数。

到目前为止,这是我的代码。

<?php

public function get_all_post(){

  $category = $this->input->post('category', true);
  
  $this->db->select('u.*,c.parent_id,b.post_id, count(b.ID) as total, count(c.ID) as totalLIKEs');
  $this->db->where('u.category', $category);
  $this->db->order_by("u.create_at", "DESC")
  ->from('gb_post as u')
  ->join('gb_comments as b', 'u.ID = b.post_id', 'LEFT')
  ->join('gb_likes as c', 'u.ID = c.parent_id', 'LEFT')
  ->group_by('u.ID');
  
  $this->db->limit(10);
  $result = $this->db->get();

  if($result->num_rows() > 0){
    return $result->result_array();
  } else {
    return false;
  }

}
?>

这是我的SQL表

发布表

+----+---------------+-----------------+
| ID | post_content  |   user_email    |
+----+---------------+-----------------+
|  1 | post1         | user1@email.com |
|  2 | post2         | user2@email.com |
|  3 | post3         | user3@email.com |
+----+---------------+-----------------+

评论表

+----+---------+-----------------+-------------------+
| ID | post_id | comment_content |   reader_email    |
+----+---------+-----------------+-------------------+
|  1 |       3 | test comment1   | reader1@email.com |
|  2 |       3 | test comment2   | reader2@email.com |
|  3 |       2 | test comment3   | reader3@email.com |
|  4 |       1 | test comment4   | reader3@email.com |
+----+---------+-----------------+-------------------+

我的喜欢表

+----+----------+-------------------+
| ID | post_id  |   reader_email    |
+----+----------+-------------------+
|  1 |        3 | reader1@email.com |
|  2 |        3 | reader2@email.com |
|  3 |        3 | reader7@email.com |
|  4 |        3 | reader3@email.com |
+----+----------+-------------------+

示例ID为3的帖子将总共有2条评论和4个赞。

问题是 totalComment 的数量也是 totalLIKEs

的数量

0 个答案:

没有答案