0

我有 3 个表,categories它们productsseller_products关联就像 CategoriesTable.php

$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'
]);

现在,在view( categories)site.com/categories/view/2中,我必须选择所有产品数据productssellerProducts其中产品属于类别 id 并且也存在于卖方产品中。IE。,

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

CakePHP 3 中是否有任何简单的方法来获得结果?

编辑 2

这就是我正在尝试的。在view()行动中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);
        }

debug它只给出表中的数据,而Products不是来自SellerProducts

4

1 回答 1

4

而不是 join 你可以简单地包含 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']);
于 2016-08-03T11:09:31.550 回答