我有两个包含客户数据的表。我需要连接两列(primaryKey 和 customer_id)。问题和解决方案描述如下: How can I join two tables on multiple columns in CakePHP 3?
还有一些表同时包含客户数据和“全局”数据。全局数据适用于所有客户,可以通过customer_id“0”来识别。
结果应如下所示:
SELECT * FROM
table1
INNER JOIN
table2
ON (table1.table2_id = table2.id AND
(table1.customer_id=table2.customer_id OR table2.customer_id=0))
WHERE 1;
是否可以(如果可以,如何)通过 CakePHP 关系来做到这一点?
UPDATE: It does not seem to work yet
$this->belongsTo('Calibrations', [
'foreignKey' => 'calibration_id',
'joinType' => 'INNER',
'conditions' => [
'Foods.calibration_id = Calibrations.id',
'OR' => [
'Foods.tenant_id' => 'Calibrations.tenant_id',
'Calibrations.tenant_id' => '0'
]
]
]);
结果
...
INNER JOIN calibrations Calibrations ON (
Foods.calibration_id = Calibrations.id
AND (
Foods.tenant_id = 'Calibrations.tenant_id'
OR Calibrations.tenant_id = 0
)
AND Calibrations.id = (Foods.calibration_id)
)
...
2nd UPDATE:
抱歉我的仓促询问,我已经找到了解决方案:
$this->belongsTo('Calibrations', [
'foreignKey' => 'calibration_id',
'joinType' => 'INNER',
'conditions' => [
'OR' => [
'Foods.tenant_id = Calibrations.tenant_id',
'Calibrations.tenant_id' => '0'
]
]
]);
结果
INNER JOIN calibrations Calibrations ON (
(
Foods.tenant_id = Calibrations.tenant_id
OR Calibrations.tenant_id = 0
)
AND Calibrations.id = (Foods.calibration_id)
)
这就是解决方案...
最佳答案
连接条件也可以表示为条件数组:
$query = $this->Table1->find()
->hydrate(false)
->join([
't2' => [
'table' => 'table2',
'type' => 'INNER',
'conditions' => [
'Table1.table2_id = t2.id',
'OR' => [
[
'Table1.customer_id' => 't2.customer_id',
't2.customer_id' => '0'
]
]
]
]
]);
另请参阅Adding Joins
UPDATE:
使用 contain()
也可以完成同样的操作:
// Table1
$this->belongsTo('Table2', [
'className' => 'Table2',
'foreignKey' => 'table2_id',
'joinType' => 'INNER',
'conditions' => [
'Table1.table2_id = Table2.id',
'OR' => [
[
'Table1.customer_id' => 'Table2.customer_id',
'Table2.customer_id' => '0'
]
]
]
]);
// Controller
$query = $this->Table1->find()
->contain('Table2');
另请参阅
关于php - CakePHP 3 属于多个具有默认值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44163554/