2016-08-27 82 views
0

我正在使用CakePHP 3.2。cakephp 3僅匹配行匹配的行

我有三個表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,符合條件的匹配給定?

回答

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

+0

這是行不通的 –

+1

如果添加的一些細節準確*如何*它不工作,那會給人什麼的一些想法修復可能是。 「不工作」太模糊,以致於不太可能獲得有用的反饋。 –