【问题标题】:Cakephp 3 select within a select complex queryCakephp 3 在选择复杂查询中选择
【发布时间】:2019-06-25 03:30:10
【问题描述】:

我有一个直接在 phpmyadmin 中运行的 mysql 选择语句。它可以找到。如何在 cakephp 3 中为此编写 mysql 语句。感谢您的帮助。

逻辑是这样的:表 product_categories 有 product_id 和 category_id 链接类别表和产品表。表 product_options 有 product_id、size、color、qty。我正在尝试根据类别显示产品,但我只想显示那些颜色为 RED 的产品。

select *from product_options, (select * FROM products Products 
left JOIN product_categories pc ON Products.id = pc.product_id
WHERE pc.category_id = 74)  as ptotals
left join product_options po ON ptotals.id = po.product_id
where po.color = 'RED'

【问题讨论】:

    标签: mysql cakephp


    【解决方案1】:

    ->matching() - 是你的朋友。开始:

    $query = $this->Products->find('all')
                ->matching('Categories')
                ->where([
                    'ProductCategories.product_id' => $category['id'],
                    'ProductCategories.category_id' => '74'];
    

    或者像他们在文档中那样做 https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#filtering-by-associated-data-via-matching-and-joins

    $query = $this->Products->find();
    $query->matching('Categories', function ($q) {
        return $q->where(['Category.id' => '74']);
    });
    

    并从那里构建您的查询。

    【讨论】:

    • Ledwon,感谢您的帮助。我确实从那里构建了查询,但得到了错误: $this->loadmodel('Products'); $pquery = $this->Products->find(); $pquery->matching('ProductCategories', function ($q) { return $q->where(['ProductCategories.category_id' => '74']); }); $pquery->JOIN([ 'table' => 'product_options', 'alias' => 'ProductOptions', 'type' => 'LEFT', 'conditions' => ['Products.id' => 'ProductOptions. product_id'] ]); $pquery->where(['ProductOptions.color' => 'RED']); $pquery->group(['Products.id']);
    • @earnest 显示完整的错误内容。您复制的内容不足以查看错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 2013-03-16
    • 2013-08-29
    • 2016-10-07
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多