Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cakephp - order by a field in the contained Model

Tags:

php

cakephp

I'm trying to get all the products which are in a particular category (products hasandbelongstomany Catrgories). My conditions are the Category.name='whatever' and the Product.live=1

I can do this like this:

$cats = $this->Category->find('all', array(
    'conditions' => array(
        'Category.name' => $categoryName
    ),
    'contain' => 'Product.live = 1'
));

But I also want to sort the results by Product.sort_order, so I tried:

$cats = $this->Category->find('all', array(
    'conditions' => array(
        'Category.name' => $categoryName
    ),
    'order' => array('Product.sort_order'),
    'contain' => 'Product.live = 1'
));

But this doesn't work. Whats the correct way to do this?

like image 830
Patrick Guinness Avatar asked Mar 18 '23 21:03

Patrick Guinness


1 Answers

TLDR: Use Joins instead of Contain (or swap the direction of find)

I've answered this question about 68 times on Stack Overflow - not sure if it's just not coming up in searches...etc or what, but - you can't order by a Contained model because Containing usually creates multiple/separate queries.

like image 154
Dave Avatar answered Apr 05 '23 06:04

Dave