the*_*ets 5 cakephp has-and-belongs-to-many
我知道 Cake HABTM 协会在最好的时候很棘手,但我似乎让自己的生活变得更加艰难......
如果我想从数据库中返回一个随机的 Item,我可以在 Item 模型中按如下方式进行:
$random = $this->find('first', array(
'order' => 'rand()'
));
Run Code Online (Sandbox Code Playgroud)
如果我想查找某个类别中的所有项目(其中项目与类别具有 HABTM 关系),我知道我可以通过 $this->Categories->find 获得结果集。
我的问题是:如何将两者结合起来,以便返回属于指定类别的随机项目?有什么简便的方法吗?(如果没有,只要它有效,我很乐意接受任何关于费力方式的建议;)
ETA:我可以通过 Containable 获得一些方法,也许:说我添加了这一行
'contain' => array('Categories'=>array('conditions'=>array('Categories.id'=>1))),
Run Code Online (Sandbox Code Playgroud)
然后我不想要的 Item 结果返回一个空的 Categories 数组,以将它们与“好”项目区分开来。但我真的不希望返回所说的项目结果......
ETA(2):如果 Categories 数组为空,我可以通过在 afterFind 中取消设置我的结果来获得解决方法(感谢http://nuts-and-bolts-of-cakephp.com/2008/08/06/filtering -results-returned-by-containable-behavior/作为提示),然后让我的随机查找函数在得到结果之前不会放弃:
while (!is_array($item)) {
$item = $this->random($cat);
}
Run Code Online (Sandbox Code Playgroud)
但是,呃,这会更笨重吗?无论如何,是时候停止编辑我的问题,而是离开并继续睡觉了!
尝试这个:
<?php
$this->Item->bindModel(array('hasOne' => array('ItemsCategory')));
$random = $this->Item->find('all', array(
'order' => 'rand()',
'conditions' => array('ItemsCategory.category_id' => '1')
));
?>
Run Code Online (Sandbox Code Playgroud)