我有4个型号:
物品------ ----的hasMany>详细
物品------ ----的hasMany>喜欢
物品------ ----的hasMany>分类
我怎样才能找到所有包含Favourite.member_id ='8'和Category.item_category_id ='1'的物品
这是我的物品模型关系:
public $hasMany = array(
'Detail' => array(
'className' => 'Detail',
'foreignKey' => 'item_id',
'dependent' => true,
'conditions' => '',
'order' => 'created DESC',
),
'Category' => array(
'className' => 'Category',
'foreignKey' => 'item_id',
'dependent' => true,
'conditions' => '',
'order' => 'created DESC',
),
'Favorite' => array(
'className' => 'Favorite',
'foreignKey' => 'item_id',
'dependent' => true,
'conditions' => '',
'order' => 'created DESC',
)
);
我使用了这个查询(),没关系:
$this->set('test',$this->Item->query("SELECT items.*
FROM items, categories, favourites
WHERE items.id = items_item_categories.item_id
AND items.id = favorites.item_id
AND categories.item_category_id = 1 AND favourites.member_id = 8"));
但是我不喜欢使用query(),我把它改成了find(),看起来不太好:
$this->set('test',$this->Item->find('all', array(
'contain'=>array(
'ItemDetail',
'Category'=>array('conditions'=>array('Category.item_category_id'=>1)),
'Favorite'=>array('conditions'=>array('Favorite.member_id'=>8)));
答案 0 :(得分:11)
您需要在模型上调用containsableBehaivor
<?php
class Item extends AppModel {
public $actsAs = array('Containable');
}
在控制器中可以进行查询
$items = $this->Item->find('all', array(
'contain'=>array(
'ItemDetail',
'Category'=>array(
'conditions'=>array('Category.item_category_id'=>1)
),
'Favorite'=>array(
'conditions'=>array('Favorite.member_id'=>8)
)
)
);
$this->set('test', $items);
尝试使用Joins
$items = $this->Item->find('all', array(
'joins' => array(
array(
'table' => 'categories',
'alias' => 'Category',
'type' => 'inner',
'conditions'=> array('Category.item_category_id' => 1)
),
array(
'table' => 'favorites',
'alias' => 'Favorite',
'type' => 'inner',
'conditions'=> array('Favorite.member_id' => 8, 'Item.id = Favorite.item_id')
)
),
'contain'=>array('ItemDetail','Category','Favorite')
);
$this->set('test', $items);
答案 1 :(得分:3)
你也可以尝试这样的事情:
$this->Item->hasMany['Favorite']['conditions']['member_id'] = 8;
与使用条件重新绑定模型具有相同的效果。
只是一个可能的问题。以上将为请求的其余部分添加条件,如果要回滚到先前的行为,则需要取消设置条件:
unset($this->Item->hasMany['Favorite']['conditions']['member_id']);
请务必将$ this-&gt; Item-&gt;递归属性设置为所需的值(recursive attribute)。默认值为1,这是您工作所需的最小值。