14

I have multiple Things in AnotherThing now I am trying to order them in my edit action in my AnotherThing Controller - I can access the Things just fine in my edit, but I want to sort them differently (not over their ID), for example Things.pos

Whats the best practice here? I tried it with

public $hasMany = array(
        'Thing' => array(
            'order' => 'Thing.pos DESC'
        )
    );

But nothing changed. Any idea?

Isengo
  • 2,004
  • 3
  • 21
  • 43

2 Answers2

33

Overread the Documentation. Sorry!

Anyways, If someone looks for an answer, here it is: http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#sorting-contained-associations

edit:

When loading HasMany and BelongsToMany associations, you can use the sort option to sort the data in those associations:

$query->contain([
    'Comments' => [
        'sort' => ['Comment.created' => 'DESC']
    ]
]);
dav
  • 8,931
  • 15
  • 76
  • 140
Isengo
  • 2,004
  • 3
  • 21
  • 43
2

If you have defined some custom finder methods in your associated table, you can use them inside contain(). For your case you can solve this like below:

$query->contain([
        'Comments' => function ($q) {
           return $q->order(['created'=>'DESC']);
        }
    ]);
Faisal
  • 4,591
  • 3
  • 40
  • 49