Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 591
MintDeparture Avatar asked Jun 27 '10 17:06

MintDeparture


3 Answers

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',
        ....
    ),
}?>
like image 183
Nik Chankov Avatar answered Sep 30 '22 17:09

Nik Chankov


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

<?php
class Post extends AppModel {
  var $hasMany = array(
    'Category' => array(
        'className' => 'Category',
        ...
        'sort' => 'Category.name DESC',
        ....
    ),
}?>
like image 34
Calderoy Avatar answered Sep 30 '22 19:09

Calderoy


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

like image 31
deceze Avatar answered Sep 30 '22 18:09

deceze