2012-10-02 104 views
2

我试图根据它们相关的类别过滤一些汽车零件。 零件可以有很多类别(在代码中称为标签),所以我选择了与连接表的HABTM关系。用AND条件过滤HABTM

过滤工作到目前为止,但只有与使用SQL命令IN蛋糕的OR条件。 但我试图过滤只有所有所选类别的部分,所以我需要在类别数组上使用AND条件。

这里的来自控制器的提取的代码:

$this->Part->bindModel(array('hasOne' => array('PartsTagsJoin'))); 

$params['conditions'] = array('AND' => array('PartsTagsJoin.tag_id' => $selectedCats)); 
$params['group'] = array('Part.id'); 

$parts = $this->Part->find('all',$params); 
$this->set('parts',$parts); 

$ selectedCats是一个这样的数组:阵列(1,2,3,4,5);

的SQL输出为:

'SELECT `Part`.`id`, `Part`.`name`, `Part`.`image`, `Part`.`image_dir`, `Part`.`time_created`, `Part`.`time_edited`, `Part`.`user_id`, `Part`.`editor_id`, `Part`.`notice`, `User`.`id`, `User`.`username`, `User`.`password`, `User`.`usergroup_id`, `User`.`realname`, `PartsTagsJoin`.`id`, `PartsTagsJoin`.`part_id`, `PartsTagsJoin`.`tag_id` 
FROM `c33rdfloor`.`parts` AS `Part` 
LEFT JOIN `c33rdfloor`.`users` AS `User` ON (`Part`.`user_id` = `User`.`id`) 
LEFT JOIN `c33rdfloor`.`parts_tags_join` AS `PartsTagsJoin` ON (`PartsTagsJoin`.`part_id` = `Part`.`id`) 
WHERE `PartsTagsJoin`.`tag_id` IN (1, 4, 8, 24)' 

我如何筛选有每一个通过$ selectedCats阵列致力于ID部分。

非常感谢您的帮助。

回答

0

我得到它的工作多亏了这篇博客文章:

http://nuts-and-bolts-of-cakephp.com/2008/08/06/habtm-and-join-trickery-with-cakephp/

这似乎是有点棘手与所有选择标记过滤条目: 实现一个与关系的关键是获取所选猫的数量并将其与组参数内的查询匹配。 这行做到了:

$params['group'] = array('Part.id','Part.name HAVING COUNT(*) = '.$numCount); 

在代码看起来像这样(有兴趣的解决方案的人)结束:

// Unbinds the old hasAndBelongsToMany relation and adds a new relation for the output 
$this->Part->unbindModel(array('hasAndBelongsToMany'=>array('PartsTag'))); 
$this->Part->bindModel(array('hasOne'=>array(
     'PartsTagsJoin'=>array(
      'foreignKey'=>false, 
      'type'=>'INNER', 
      'conditions'=>array('PartsTagsJoin.part_id = Part.id') 
     ), 
     'PartsTag'=>array(
       'foreignKey'=>false, 
       'type'=>'INNER', 
       'conditions'=>array(
        'PartsTag.id = PartsTagsJoin.tag_id', 
        'PartsTag.id'=>$selectedCats 
))))); 

$numCount = count($selectedCats); // count of the selected tags 

// groups the entries to the ones that got at least the count of the selected tags -> here the 'AND' magic happens 
$params['group'] = array('Part.id','Part.name HAVING COUNT(*) = '.$numCount); 

$parts = $this->Part->find('all', $params); // sends the query with the params 

$this->set('tagCategories', $categories); 
$this->set('selectedCats', $selectedCats); 
$this->Part->recursive = 4; 
$this->set('parts',$parts);