CafeHey
CafeHey

Reputation: 5800

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 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.

Upvotes: 5

Views: 9385

Answers (5)

Irshad Khan
Irshad Khan

Reputation: 6046

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;

Upvotes: 0

Calderoy
Calderoy

Reputation: 41

in cakephp 3 use 'sort' instead of 'order':

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

Upvotes: 4

Nik Chankov
Nik Chankov

Reputation: 6047

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',
        ....
    ),
}?>

Upvotes: 23

deceze
deceze

Reputation: 522024

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

Upvotes: 3

Jason McCreary
Jason McCreary

Reputation: 72971

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.

Upvotes: 0

Related Questions