0
votes

I extended the CakePHP Blog Tutorial, and added Categories for my Posts. The Posts Model belongsTo the Category Model. In my Posts View I am looping threw my Categories table to list the Categories for a Menu in the View, which works fine:

/* gets the category names for the menu */
$this->set('category', $this->Post->Category->find('all'));

Now I am trying to add the Post count to each Menu (Category) Item. So far I got this:

/* gets the category count for category 2*/
$this->set('category_2_count', $this->Post->find('count', array(
'conditions' => array('Category.id =' => '2'))));

The Problem is that I obviously can't use the Loop in my View anymore. With this I have to get each Category + each Count, which seems very inelegant. Is there a way to query the Category Names and the Count and get one Array for the View?

Any Ideas? I am new to Cake and any help is greatly appreciated.

2

2 Answers

0
votes

In your controller:

$this->set('category', $this->Post->Category->find('all', array(
    'fields' => array(
        '*',
        '(SELECT COUNT(*) FROM posts WHERE category_id = Category.id) AS `post_count`'
    )
)));

In your view:

foreach ($category as $c) {
    echo $c['Category']['name']; // category name
    echo $c[0]['post_count']; // post count
}
0
votes

try this:

$stats = $this->Category->Post->find('all', array(
    'fields' => array(
        'Category.*',
        'COUNT(Post.id) AS cnt'
    ),
    'group' => 'Category.id'
));