PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, February 17, 2022

[FIXED] CakePHP 3 Sort Associative data DESC using order

 February 17, 2022     cakephp     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing