hairynuggets
hairynuggets

Reputation: 3311

How to count items in group with Codeigniter?

I am using active record to return a grouped list of dates with the following code:

function get_archive_links(){

        $this->db->order_by('date','desc');
        $this->db->group_by('MONTH(date), YEAR(date)');
        $query = $this->db->get('blog'); 

    foreach ($query->result() as $row) {
        $data[] = array(
            'id' => $row->id,
            'date' => $row->date
        );
    }

    return $data;
}

Which when looped and echoed on my page returns:

How can I count each item in the group and display it in my list? Example:

I will be counting how many blog posts there where for each month.

Upvotes: 1

Views: 12935

Answers (4)

shimara
shimara

Reputation: 1

SELECT
  categories.*,
  COUNT(posts.category_id) AS `count`
FROM
  (categories
LEFT JOIN
    posts 
ON posts.category_id = categories.category_id)
GROUP BY
  Category_name;

I've got the answer for the zero count issue.

Upvotes: 0

irfan
irfan

Reputation: 1

This works perfect but not shows zero counts if not exist post for category

here is my function,

function get_category_list()
{
    $this->db->select("count(*) as num_posts,cb_category.*");
    $this->db->where_in('cb_post.city', $city_ids);
    $this->db->join('cb_posts', 'cb_post.category = cb_category.cat_id or cb_post.parent = cb_category.cat_id', 'left');

    $this->db->order_by('cat_name_en', 'ASC');

    $this->db->group_by('cb_category.cat_id');

    $query = $this->db->get('cb_category');

}

Upvotes: 0

levye
levye

Reputation: 235

You can it with sql count function. if you are using group by, count function returning count rows for row group.

like this,

function get_archive_links(){
    $this->db->select("count(*) as count, blog.*);
    $this->db->order_by('date','desc');
    $this->db->group_by('MONTH(date), YEAR(date)');
    $query = $this->db->get('blog'); 

    foreach ($query->result() as $row) {
        $data[] = array(
            'id' => $row->id,
            'date' => $row->date,
            'count' => $row->count
        );
    }

return $data;

}

Upvotes: 1

Joe
Joe

Reputation: 15812

You need to either remove the GROUP BY then count in PHP, or add a ->select('COUNT(id) AS num_posts') to your AR query. I'd probably add the ->select(), as it's less work :)

Upvotes: 2

Related Questions