phpmysqlcodeignitercountquery-builder

Count the rows from a joined table with CodeIgniter's query builder


I know how to join two tables, but I'd like to actually count the number of rows in the joined/second table with CodeIgniter's query builder methods.

Say, I have these two tables:

blog     comments
-------  ----------
id       id
title    blog_entry_id
content  comment

I want to take the three last blog entries and count the number of comments per blog entry, all in one query. I unsuccessfully tried using count_all_results() like this:

$this->db->select('*')
         ->from('blog')
         ->order_by('blog.id', 'desc')
         ->limit(3);

$this->db->join('comments', 'blog_entry_id = blog.id')
         ->group_by('blog_entry_id')
         ->count_all_results('comments'); 

The above script produces an unintended query and incorrectly returns a numeric result not larger than 3:

SELECT COUNT(*) AS `numrows`
FROM (
    SELECT *
    FROM `blog`, `comments`
    JOIN `comments` ON `blog_entry_id` = `blog`.`id`
    GROUP BY `blog_entry_id`
    LIMIT 3
)

What should I do? What am I doing wrong?


Solution

  • Got it! :)

    $this->db->select('blog.*, COUNT(comments.id) as num_comments')
             ->from('blog')
             ->order_by('blog.id', 'desc')
             ->limit(3);
    
    $this->db->join('comments', 'blog_entry_id = blog.id')
             ->group_by('blog_entry_id');