Reputation: 4464
I know this question is very simple. But I fail to find it in Google. I'm very new to cake afterall.
For example I have two Model: Product
and Category
.
In Product index
I want to show a list of available Categories and the amount of Products in that category. Like below:
Food (10)
Beverages (7)
...
I successfully looped the available categories, but not sure how to count it. Below is my loop:
<?php foreach($categories as $c): ?>
<li> ... <?php echo $this->$c->Product->find('count') ?> </li>
<?php endforeach; ?>
// The ... part is echo-ing the category name
I tried many variations and keep getting error like ArrayHelper not found
or ProductHelper not found
Anyone have the solution?
Thanks
EDIT
This is my ProductController code before I added the foreach
loop you suggested.
public function index() {
//the first two lines is default from cake bake
$this->Product->recursive = 0;
$this->set('products', $this->paginate());
$categories = $this->Product->Category->find('all');
$this->set('categories', $categories);
}
Upvotes: 0
Views: 151
Reputation: 8100
Instead of calculating the count on each request, use the counter cache feature to store the products count for each category and then simply display that.
Upvotes: 2
Reputation: 100195
you are trying to call model
in view file, instead you could add the product count to your array from controller itself, like, example code would be:
in your controller:
$categories = $this->Product->Category->find('all',array('recursive'=>-1));
foreach($categories as $key => $category){
$categories[$key]['ProductCount'] = $this->Product->find('count',
array(
'conditions'=>array('Product.category_id'=>$category['Category']['id'])
)
);
}
where ProductCount
can be replaced by name of the product
Upvotes: 1