cakephp 3仅在行存在时才匹配

时间:2016-08-27 04:17:48

标签: cakephp cakephp-3.2

我正在使用CakePHP 3.2。

我有三个表categoriesproductsseller_products

我想从所有表中检索数据,其中seller_products.stock > 0seller_products.status = 1也是GROUP BY categories

此代码工作正常

$pros1 = $this->Products->Categories->find()
    ->where([
    ])
    ->select(['Categories.id', 'Categories.title'])
    ->distinct(['Categories.id'])
    ->contain([
        'Products' => ['conditions' => ['status' => 1]], 'Products.SellerProducts',
    ])
    ->matching('Products.SellerProducts', function(\Cake\ORM\Query $q) {
    return $q->where(['SellerProducts.stock >' => 0, 'SellerProducts.status' => 1]);
});

他们的关联是

$categories->hasMany('Products', [
   'foreignKey' => 'category_id'
]);
$products->hasMany('SellerProducts, [
   'foreignKey' => 'product_id'
]);

现在,问题是。

此查询甚至会返回SellerProducts.product_id

中未退出的产品

如何只获得SellerProducts中存在且满足匹配条件的产品?

1 个答案:

答案 0 :(得分:0)

您需要使用内部联接查询进行调用。请尝试以下代码:

$pros1 = $this->Products->Categories->find()
        ->where([])
        ->select(['Categories.id', 'Categories.title'])
        ->distinct(['Categories.id'])
        ->contain([
            'Products' => ['conditions' => ['status' => 1]], 'Products.SellerProducts',
        ])
        ->innerJoinWith('Products.SellerProducts', function(\Cake\ORM\Query $q) {
            return $q->where(['SellerProducts.stock >' => 0, 'SellerProducts.status' => 1]);
        });

有关详细信息,请访问http://book.cakephp.org/3.0/en/orm/query-builder.html#using-innerjoinwith