views:

71

answers:

3

Hi,

When I search a model which "has many" of something else.

For example a blog post has many categories.

When searching for blog post with categories associated, how do I order the associated categories? When the array is returned it ignores the order on the category model and defaults to it's usual id order.

Cheers.

A: 

You can specify the order attribute of the find method parameters. Otherwise, it will default to the order for the top-most/parent Model. In your case the Category.id.

Jason McCreary
The associated model is ordered on the model itself, where do you add it it the find when your getting associated 'has many' on a model?
Smickie
Post the code that you are using to retrieve your model data or take a look at http://book.cakephp.org/view/1018/find. I believe you want set the `order` parameter.
Jason McCreary
+2  A: 

You can do this with the ContainableBehavior:

$this->Post->find('all', array('contain' => array(
    'Category' => array(
        'order' => 'Category.created DESC'
    )
)));

http://book.cakephp.org/view/1325/Containing-deeper-associations

deceze
+3  A: 

In addition you can set the order in your model's relation.

<?php
class Post extends AppModel {
  var $hasMany = array(
    'Category' => array(
        'className' => 'Category',
        ...
        'order' => 'Category.name DESC',
        ....
    ),
}?>
Nik