CakePHP 3:多级关联

CakePHP 3 : multi level association

我有 3 个 table、categoriesproductsseller_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'
]);

卖家ProductsTable.php

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

现在,在 categories (site.com/categories/view/2) 的 view 中,我必须 select 来自 productssellerProducts 的所有产品数据] 其中products属于category id,也存在于sellerProducts中。 即,

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

在 CakePHP 3 中有没有简单的方法来获得结果?

Edit 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 table 的数据而不是来自 SellerProducts

您可以简单地包含 SellerProducts 而不是加入

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

如果你想查询sellerproducts的数据你可以

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