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!

This entry was posted on Wednesday, March 24th, 2010 at 5:55 pm and is filed under Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

3 Responses to “CakePHP containable order”

  1. RenaeNo Gravatar Says:

    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. RenaeNo Gravatar Says:

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

  3. CakeFreakNo Gravatar Says:

    Thanks for sharing. This saved me a lot of time.

Leave a Reply


Warning: Undefined variable $user_ID in /home/curtis/curtisgibby.com/blog/wp-content/themes/stylized/comments.php on line 77