Cakephp 3在选择复杂查询中选择

时间:2019-06-25 03:30:10

标签: mysql cakephp

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

逻辑是这样的:表product_categories具有将category表和product表链接的product_id和category_id。表product_options具有product_id,大小,颜色,数量。我试图显示基于类别的产品,但是我只想显示红色的产品。

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'

1 个答案:

答案 0 :(得分:0)

-> 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']);
});

并从那里构建查询。