在我的OrdersTable.php
中:
$this->hasOne('Total', [
'className' => 'App\Model\Table\TotalsTable',
'foreignKey' => 'order_id',
'propertyName' => 'Total'
]);
实际totals
表:
| id | order_id | type | value |
|----|----------|----------|-------|
| 1 | 1 | total | 100 |
| 2 | 1 | tax | 20 |
| 3 | 1 | shipping | 5 |
结构和逻辑来自opencart/opencart,我对此无能为力。
这是一个非功能性的概念:
$query = $ordersTable->find('all', array(
'contain' => array(
'TotalTax' => [
'associationName' => 'Total',
'conditions' => function($query) {
return $query->where([
'TotalTax.type' => 'tax',
]);
},
],
'TotalShipping' => [
'associationName' => 'Total',
'conditions' => function($query) {
return $query->where([
'TotalShipping.type' => 'shipping',
]);
},
],
),
));
你们认为这样的事情可行吗?
UPD :由于每个type
可能太多,因此无法创建关联
答案 0 :(得分:0)
如果此功能可以在您的代码库中重复使用,我将在表级别实现此逻辑,并具有两个不同的条件关联:
在OrdersTable.php
$this->hasOne('TotalTax', [
'className' => 'Totals'
])
->setConditions(['TotalTax.type' => 'tax'])
->setDependent(true);
$this->hasOne('TotalShipping', [
'className' => 'Totals'
])
->setConditions(['TotalShipping.type' => 'shipping'])
->setDependent(true);
然后您可以在查询中简单地包含它们:
$query = $ordersTable->find()->contain(['TotalTax', 'TotalShipping'];
中找到此示例