2012-12-03 76 views
0

我在cakephp 2.1中找到了一个自定义查找结构。Cakephp IN(x,x)with'AND'

在我的模型我有这样的功能:

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') 
     ) 

查询的结果返回的项目关联是“喜剧”或“惊悚”流派给他们。

如何修改查询以仅返回与他们相关的'Comedy'和'Thriller'流派的项目?

有什么建议吗?

编辑:数据

内容是:

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

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

回答

4

你会希望你的'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); 
} 
+0

非常感谢! – 3und80