2016-08-03 54 views
0

我有3個表,categoriesproductsseller_products及其關聯就像 CategoriesTable.phpCakePHP的3:多級聯想

$this->hasMany('Products', [ 
    'foreignKey' => 'category_id' 
]); 

ProductsTable.php

$this->hasMany('SellerProducts', [ 
    'foreignKey' => 'product_id' 
]); 

$this->belongsTo('Categories', [ 
    'foreignKey' => 'category_id', 
    'joinType' => 'INNER' 
]); 

SellerProductsTable.php

$this->belongsTo('Products', [ 
    'foreignKey' => 'product_id', 
    'joinType' => 'INNER' 
]); 

現在,在categoriesviewsite.com/categories/view/2),我不得不從productssellerProducts選擇所有產品數據,其中產品所屬類別ID,也存在於sellerProducts。 即,

products.category_id = $id AND sellerProducts.product_id = Products.id 

有CakePHP中3任何簡單的方法來獲得結果呢?

編輯2

這就是我正在努力。在CategoriesController.php

$this->loadModel('Products'); 
     $sellerProducts = $this->Products->find('all', [ 
      'conditions' => [ 
      'category_id' => $id 
      ], 
      'joins' => [ 
       'table' => 'SellerProducts', 
       'alias' => 'SellerProducts', 
       'type' => 'INNER', 
       'conditions' => [ 
       'SellerProducts.product_id' => 'Products.id', 
       'stock >' => 0 
       ] 
      ] 
     ]); 
     debug($sellerProducts); 
     foreach($sellerProducts as $a) { 
      debug($a); 
     } 

debugview()行動也只給出從Products表,但沒有從SellerProducts

+0

似乎是一個非常簡單的任務,你到底嘗試了什麼? – arilia

+0

@arilia參見'edit 2' –

回答

2

,而不是加入你們可以只包含SellerProducts

$this->Products->find() 
    ->where(['category_id' => $id]) 
    ->contain(['SellerProducts' => function($q) { 
     return $q->where(['stock >' => 0]) 
    }]); 

,如果你想查詢數據您可以做的賣家產品的數據

$this->Products->SellerProducts->find() 
    ->where([ 
     'Products.category_id' => $id 
     'SellerProducts.stock >' => 0]) 
    ->contain(['Products', 'Products.Categories']); 
+0

這給出了'2D'數組中的結果,其中第一個數組包含'products',第二個數組包含與該產品相關的所有'sellerProducts'。我想要單個數組中的所有數據,因爲稍後需要運行許多其他函數才能找到'sellerProducts'中的'min('selling_price')'和max('selling_price')'。並且每個產品只有一個銷售者只有最低的'selling_price'等,我只能得到一個銷售者。我認爲稍後加入這個功能會很容易。 –

+0

我添加了一個替代解決方案,請參閱我的編輯 – arilia