4

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?

scrowler
  • 24,273
  • 9
  • 60
  • 92
Patrick Guinness
  • 387
  • 1
  • 6
  • 19

1 Answers1

7

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.

Community
  • 1
  • 1
Dave
  • 28,833
  • 23
  • 113
  • 183
  • OMG @scrowler - you found and linked them all. I wish I could +1 you for that. Made me LOL. – Dave Aug 01 '14 at 03:59