我正在使用CakePHP 3.2。
我有三个表categories
,products
和seller_products
我想从所有表中检索数据,其中seller_products.stock > 0
和seller_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
中存在且满足匹配条件的产品?
答案 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