Thursday, February 17, 2022

[FIXED] CakePHP 3 Sort Associative data DESC using order

Issue

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!


Solution

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'));


Answered By - Ved

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.