2016-08-03 57 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