已经很晚了,我已经编写了这个庞大的查询以根据我已经找到的产品获取相关产品。
我需要获取同一类别的产品 (HABTM)、父产品、具有相同父产品(兄弟/邻居)的产品以及当前产品的直接子产品(只有一层嵌套).我有当前产品的产品 ID 及其 parent_id。如果可以像 Product.published = 1
一样为产品设置条件,那会很棒,但如果它会使查询变得如此之大,我总是可以在之后进行检查。此外,我需要排除当前产品。
SELECT `products`.*
FROM `products`, `categories_products`
WHERE
(
(
`categories_products`.`product_id` = `products`.`id`
AND `categories_products`.`category_id` IN (
SELECT `category_id`
FROM `categories_products`
WHERE `categories_products`.`product_id` = '$product_id'
)
)
OR `products`.`parent_id` = '$parent_id'
OR `products`.`parent_id` = '$product_id'
OR `products`.`id` = '$parent_id'
)
AND `product`.`id` <> '$product_id'
GROUP BY `products`.`id`
甚至有可能进一步优化它,到目前为止我已经:
public function related($productData, $limit = 4) {
$conditions = array(
'OR' => array(array('Product.parent_id' => $productData['Product']['id'])), // Children of product),
'Product.id <>' => $productData['Product']['id']
);
if(!empty($product['parent_id'])) {
$conditions['OR'][] = array('Product.parent_id' => $productData['Product']['parent_id']); // Siblings
$conditions['OR'][] = array('Product.id' => $productData['Product']['parent_id']); // Parent of product
}
return $this->find('all', array(
'conditions' => $conditions,
'contain' => array('Category'),
'group' => 'Product.id',
'limit' => $limit
));
}
最佳答案
您将需要使用蛋糕的 Complex Find Conditions syntax (向下滚动到子查询部分)。
关于mysql - 将这个带有 HABTM 相关数据的巨大查询转换为 CakePHP 查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8828103/