【问题标题】:Cakephp IN(x,x) with 'AND'Cakephp IN(x,x) 与 'AND'
【发布时间】:2012-12-03 13:56:21
【问题描述】:

我正在为 cakephp 2.1 中的自定义查找而苦苦挣扎。

在我的模型中,我有这个功能:

public function findByGenres($data = array()) {
        $this->Item2genre->Behaviors->attach('Containable', array('autoFields' => false));
        $this->Item2genre->Behaviors->attach('Search.Searchable');
        $query = $this->Item2genre->getQuery('all', array(
            'conditions' => array('Genre.name'  => $data['genre']),
            'fields' => array('item_id'),
            'contain' => array('Genre')
        ));
        return $query;
    }

这将返回以下查询:

SELECT `Item`.`id` FROM `items` AS `Item` 
     WHERE `Item`.`id` 
       IN(SELECT `Item2genre`.`item_id` FROM `item2genre` AS Item2genre 
          LEFT JOIN `genres` AS Genre ON(`genre_id` = `Genre`.`id`) 
              WHERE `Genre`.`name` 
                IN ('Comedy', 'Thriller')
         ) 

查询的结果返回与它们相关联的“喜剧”或“惊悚”类型的项目。

如何修改查询以仅返回与其相关联的“喜剧”和“惊悚”类型的项目?

有什么建议吗?

编辑:

数据内容为:

'genre' => array(
                (int) 0 => 'Comedy',
                (int) 1 => 'Thriller'
            )

【问题讨论】:

  • $data['genre']的内容是什么?

标签: arrays cakephp find cakephp-2.1


【解决方案1】:

您希望您的 'conditions' 密钥是这样的:

'conditions' => array(
    array('Genre.name' => 'Comedy'),
    array('Genre.name' => 'Thriller')
)

所以特别针对您的问题,您的$data['genre']array('Comedy', 'Thriller')。因此,您可以创建一个内容与您需要的内容相似的变量:

$conditions = array();
foreach ($data['genre'] as $genre) {
    $conditions[] = array('Genre.name' => $genre);
}

【讨论】:

    猜你喜欢
    • 2012-09-25
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多