Cakephp, ordering associated tables
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 o开发者_JS百科rder 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.
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',
....
),
}?>
in cakephp 3 use 'sort' instead of 'order':
<?php
class Post extends AppModel {
var $hasMany = array(
'Category' => array(
'className' => 'Category',
...
'sort' => 'Category.name DESC',
....
),
}?>
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
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
.
Sorting by columns in associated models requires setting sortWhitelist
.
$this->paginate['order'] = [ 'Fees.date_incurred' => 'desc' ];
$this->paginate['sortWhitelist'] = ['Fees.date_incurred', 'Fees.amount'];
$this->paginate['limit'] = $this->paginate['maxLimit'] = 200;
精彩评论