下面的腳本解決了我的問題的產生,像這樣的查詢:
PHP
$data = $this->Designer->find(
'first',
array(
'conditions' => array(
'Designer.slug' => $name,
'Designer.available' => 1
)
)
);
$inc_tag_ids = array();
$exc_tag_ids = array();
foreach($data["Tag"] as $tag)
{
if($tag['DesignersTag']['include'])
{
$inc_tag_ids[] = $tag['id'];
}
else
{
$exc_tag_ids[] = $tag['id'];
}
}
$ins = ' ';
if(count($inc_tag_ids))
{
$inc_tag_id_str = '"' . implode('","',$inc_tag_ids) . '"';
$ins .= 'AND tags.id IN ('.$inc_tag_id_str.')';
}
if(count($exc_tag_ids))
{
$exc_tag_id_str = '"' . implode('","',$exc_tag_ids) . '"';
$ins .= 'AND products.id NOT IN (
SELECT products.id
FROM products, products_tags, tags
WHERE products.id = products_tags.product_id
AND tags.id = products_tags.tag_id
AND tags.id IN ('.$exc_tag_id_str.')
)';
}
$prod_qry = '
SELECT *, COUNT(DISTINCT tags.name) AS uniques
FROM products, products_tags, tags
WHERE products.id = products_tags.product_id
AND tags.id = products_tags.tag_id
'.$ins.'
GROUP BY products.id
HAVING uniques = '.count($inc_tag_ids).'
';
echo $prod_qry;
$data["matching_products"] = $this->Designer->Tag->query($prod_qry);
SQL
SELECT * , COUNT(DISTINCT tags.name) AS uniques
FROM products, products_tags, tags
WHERE products.id = products_tags.product_id
AND tags.id = products_tags.tag_id
AND tags.id
IN (
"8"
)
AND products.id NOT
IN (
SELECT products.id
FROM products, products_tags, tags
WHERE products.id = products_tags.product_id
AND tags.id = products_tags.tag_id
AND tags.id
IN (
"7"
)
)
GROUP BY products.id
HAVING uniques =1
但是我覺得這不是CakePHP的是inteded的方式被對待,我想也許這應該在模型中處理,而不是在控制器中處理。但我不知道該怎麼做。