gpt4 book ai didi

cakephp - 使用hasMany模型查找条件

转载 作者:行者123 更新时间:2023-12-04 16:48:24 25 4
gpt4 key购买 nike

我有4个模型:

项目------有很多---->详细

项目------有很多---->收藏

项目------有很多---->类别

如何找到所有具有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',
)

);

我使用了这个query(),没关系:
$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)));

最佳答案

您需要在模型上调用containableBehaivor

<?php
class Item extends AppModel {
public $actsAs = array('Containable');
}

在您的 Controller 中,您可以进行查询
$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);

关于cakephp - 使用hasMany模型查找条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10344315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com