JP Arcilla
JP Arcilla

Reputation: 29

CakePHP 3 Sort Associative data DESC using order

I am fairly new in cakePHP. I have a Blogs and Comments table having a one-to-many relationship. In the blogs controller, I have this code to get the blog data and the attached comments to it.

$blog = $this->Blogs->get($id, contain => ['Comments']);
$this->set(compact('blog'));

I am trying to populate the data of the Comments by using a foreach loop.

foreach ($blog->comments as $comment) :
echo $comment.'<br />';
endforeach;

However, the default order is ascending based on the id of the Comments table, and what I am trying to achieve is a DESC order based on Comments.created , so when I populate the data, the top most would be the latest created comment and so on.. Any kind of help is greatly appreciated!

Upvotes: 1

Views: 98

Answers (1)

Ved
Ved

Reputation: 746

You can provide extra information in contain. https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#sorting-contained-associations

$blog = $this->Blogs->get($id, contain => ['Comments' => ['sort' => ['Comments.created' => 'DESC']]]);
$this->set(compact('blog'));

Upvotes: 2

Related Questions