cakephp 3仅在行存在时才匹配

cakephp 3 matching only if row exists

我正在使用 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中存在的且满足匹配条件的产品?

您需要调用内连接查询。请尝试以下代码:

$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