CakePHP containable order

I’m developing in CakePHP at work, and I was trying to do a sort on a contained model.   As in, for all of the Foos, get all the related Bars, but order the Bars by Bar.publish_date (or whatever).

I kept getting conflicting information about whether that was even possible and how to go about it.   I also got the following error several times: Model “Foo” is not associated with model “order” — it thought I was trying to sub-contain “order” into Foo->Bar.   I eventually figured out that I had one too many parenthesis on the contain conditions (i.e. which Bars to get).   This is what I ended up with that worked correctly.

$this->Foo->contain(array(
	'Bar' => array(
		'conditions' => 'Bar.publish_date <= "'.date("Y-m-d H:i:s",time()).'"', // only get the bars that have been published
		'order' => 'Bar.publish_date asc' // sort bars by pubdate
	),
));
$foo = $this->Foo->findbyId($foo_id); // or whatever other kind of find you need

Hope this helps someone in the future!

3 comments

  1. Um sure, maybe I’ll try to jump up and catch a corner of whatever that was that just flew right over my head. Good job figuring out your conundrum!

  2. I could also say something about fubar, but that would be inappropriate. I guess I’m going to the bad place now.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.