mysql - 将这个带有 HABTM 相关数据的巨大查询转换为 CakePHP 查找

标签 mysql cakephp join has-and-belongs-to-many

已经很晚了,我已经编写了这个庞大的查询以根据我已经找到的产品获取相关产品。

我需要获取同一类别的产品 (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/

相关文章:

mysql - Apache Drill - 查询 HDFS 和 SQL

php - 如何插入限制帖子的分页?

php - Sphinx 重新启动搜索恶魔问题以重新索引 Delta 索引

MySQL 加入 3 个表

php - 只需 1 个查询即可增加 View 表?

php - 洞察查询优化

javascript - 如何将 PHP 嵌入 Javascript 函数中?

php - 在 CakePHP 中使用 Simpletest 缺少表

json - 合并 JSON 文件但保留空键(最好使用 JQ)

sql-server - ssis 合并连接转换左外连接,其中 col 为空