循环中的CakePHP计数

循环中的CakePHP计数,cakephp,loops,count,items,Cakephp,Loops,Count,Items,我扩展了CakePHP博客教程,并为我的文章添加了类别。Posts模型属于Category模型。在我的帖子视图中,我正在循环我的类别表,以列出视图中菜单的类别,这很好: /* gets the category names for the menu */ $this->set('category', $this->Post->Category->find('all')); 现在我正在尝试将Post计数添加到每个菜单(类别)项中。到目前为止,我得到了这个: /* gets

我扩展了CakePHP博客教程,并为我的文章添加了类别。Posts模型属于Category模型。在我的帖子视图中,我正在循环我的类别表,以列出视图中菜单的类别,这很好:

/* gets the category names for the menu */
$this->set('category', $this->Post->Category->find('all'));
现在我正在尝试将Post计数添加到每个菜单(类别)项中。到目前为止,我得到了这个:

/* gets the category count for category 2*/
$this->set('category_2_count', $this->Post->find('count', array(
'conditions' => array('Category.id =' => '2'))));
问题是我显然不能再在我的视图中使用循环了。有了这个,我必须得到每个类别+每个计数,这似乎很不雅观。是否有方法查询类别名称和计数,并为视图获取一个数组

有什么想法吗?我刚接触蛋糕,非常感谢您的帮助。

试试这个:

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

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

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

但是我不能首先访问类别模型:“尝试获取非对象的属性”。在上面添加这一行:
Controller::loadModel('Category')