我有3个表,categories
,products
和seller_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
)的products
中,我必须从sellerProducts
和products.category_id = $id AND sellerProducts.product_id = Products.id
中选择产品所属的所有产品数据id也存在于sellerProducts中。
即,
view()
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);
}
行动中
debug
在Products
上,它仅提供来自SellerProducts
表的数据,但不提供来自Login 11:30,
Login 11:30,
Logout 11:30,
Login 11:30,
Logout 09:30,
Login 09:30
的数据
答案 0 :(得分:2)
代替加入,您只需包含SellerProducts
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 1
On-line CPU(s) list: 0
Thread(s) per core: 1
Core(s) per socket: 1
Socket(s): 1
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 62
Model name: Intel(R) Xeon(R) CPU E5-2670 v2 @ 2.50GHz
Stepping: 4
CPU MHz: 2500.046
BogoMIPS: 5000.09
Hypervisor vendor: Xen
Virtualization type: full
L1d cache: 32K
L1i cache: 32K
L2 cache: 256K
L3 cache: 25600K
NUMA node0 CPU(s): 0
RAM = 2 GB
如果您想查询来自卖方产品的数据,您可以
$this->Products->find()
->where(['category_id' => $id])
->contain(['SellerProducts' => function($q) {
return $q->where(['stock >' => 0])
}]);