简体   繁体   中英

Counting number of articles within a category using CakePHP?

I have a simple cakephp app with table articles that has a cat_id column to reference a id column of categories in a cats table.

What I would like to do is display all categories names, each followed with a count of the number of articles belonging to that category.

I know there is a find('count') function in cakephp , but that only working on one table/field. How do I link the two tables to get a list of category names and count of articles for each category for my view?

Thanks

COme on! Use counterCache! In table "cats" create field article_count. In Model write

/app/models/cat.php
class Cat extends AppModel
{
   var $name = 'Cat';
   var $belongsTo = array('Article'=>array('counterCache'=>true));
}

That's all! every time you add/remove from articles, it writes to cats table count of articles. don't forget to include article_count into fields list

it might be better to do this in the afterFind callback on the model but can be done in the controller aswell.

$cats - $this->Cat->find('all',array('recursive'=>-1));
foreach($cats as $key=>$cat){
  $cats[$key]['ArticleCount'] = $this->Cat->Article->find('count',array(
     'conditions'=>array('Article.cat_id'=>$cat['Cat']['id']))
  );
}

or see if this works

$cats = $this->Cat->find('all',array('contain'=>array(
          'Article'=>array('fields'=>array('COUNT(*) AS ArticleCount')
        )));

obviously you will need to add the containable behavior on the category model.

您还可以使用计数器缓存功能: http : //book.cakephp.org/view/816/counterCache-Cache-your-count

您也可以考虑检出counterCache以将计数缓存在列值中。

Thanks, this worked:

        $cats = $this->Article->Cat->find('all',array('recursive'=>-1));
    foreach($cats as $key=>$cat){
      $cats[$key]['ArticleCount'] = $this->Article->find('count',array(
         'conditions'=>array('Article.cat_id'=>$cat['Cat']['id']))
      );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM