Cake HABTM Query Order By Rand ()

I know Cake HABTM associations are complex in the best of times, but I seem to make life even more difficult for myself ...

If I want to return a random item from db, I can do it as follows in the Item model:

$random = $this->find('first', array( 'order' => 'rand()' )); 

and if I want to find all the elements that are in a certain category (where Item has HABTM related to categories), I know that I can get the result set via $ this-> Categories-> find.

My question is: how can I combine the two, so I can return a random item belonging to a certain category? Is there an easy way? (If not, I will be happy to accept any labor-intensive work if it works;)

ETA: I can get part of the path with Containable, perhaps: let's say I add a line

 'contain' => array('Categories'=>array('conditions'=>array('Categories.id'=>1))), 

then the result of the Item, which I do not want to return with an empty array of categories, to distinguish them from the "good" elements. But actually I do not want the results of the element to be returned at all ...

ETA (2): I can get a workaround by deleting my results in afterFind if the array of categories is empty (thanks to http://nuts-and-bolts-of-cakephp.com/2008/08/06/filtering-results-returned -by-containable-behavior / for the tip), and then when my random search function doesn't give up until it gets the result:

 while (!is_array($item)) { $item = $this->random($cat); } 

but maybe it could be some kind of clunkier? In any case, it’s time for me to stop editing my question and leave and sleep on it instead!

+4
source share
1 answer

Try the following:

 <?php $this->Item->bindModel(array('hasOne' => array('ItemsCategory'))); $random = $this->Item->find('all', array( 'order' => 'rand()', 'conditions' => array('ItemsCategory.category_id' => '1') )); ?> 
+4
source

All Articles