2012-12-03 72 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