EDIT – I was able to fix this problem using code from ‘Farray’ with the following changes:
$categories = $this->Category->find(
'all',
array(
'fields' => array(
'Category.id',
'Category.title'
),
'order' => 'Category.title ASC',
'contain' => array(
'Article' => array(
'fields' => array(
'Article.id',
'Article.title',
'Article.slug',
'Article.main_image'
),
'conditions' => array(
'published' => 1
),
'order' => 'Article.id DESC',
'limit' => 4
)
)
)
);
==================================================================================
My app has an Articles controller as well as Categories controller. I want to display all my categories on the bottom of my Articles’ index and for each Category I want to display 4 articles per the following:
Category 1
article 1
article 2
article 3
article 4
Category 2
article 1
article 2
article 3
article 4
etc...
Currently I am accomplishing this using the following code in my index.ctp
foreach($categories as $category){
echo $category['Category']['title'];
$this->element('related_articles', array('categoryID'=>$category['Category']['id']));
}
Basically, I go thru all available categories and for each category in foreach
- I call an element to get related articles
- This element uses requestAction to call a Categories controller action which return related articles
- Once again, I go thru foreach to display all related articles
This process is repeated for every Category that I have. Obviously this is not the best way to do this. What is the best way?
The following is what I use in my Articles Controller view function for categories:
$categories = $this->Article->Category->find(
'all',
array(
'fields' => array(
'Category.id',
'Category.title'
),
'order' => 'Category.id DESC',
'recursive' => 1,
'limit' => 1
)
);
With this, my load time gets decreased considerably and if I can find another faster way that would be great…
Use the Containable model behavior and you should be able to do something like this:
This would get all categories, and 4 articles for each category. I haven’t touched 1.3 in a while so I might be slightly off on the syntax, but this is the way Cake likes to limit model fetches. If you use Containable a lot, you can set it in the model definition (or in AppModel if you want it to apply to all models).