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!
March 26th, 2010 at 6:27 am
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!
March 26th, 2010 at 7:54 am
I could also say something about fubar, but that would be inappropriate. I guess I’m going to the bad place now.
April 21st, 2014 at 12:51 pm
Thanks for sharing. This saved me a lot of time.