如何创建通过 OR 条件加入多个外键的 hasOne 关联?
How to create a hasOne association that joins on multiple foreign keys via an OR condition?
我正在尝试从另一个 table(端口)两次加入 table(连接)。
条件是:
- 一个端口可以有一个或没有连接
- 一个连接有一个从端口和一个到端口
结构是:
Table 端口:
- id
- 人数
Table 连接数:
- id
- port_from_id
- port_to_id
- 名字
所以现在我想从 Ports 加入 Connections。
蛋糕总是给我这个:
LEFT JOIN connections Connections ON Ports.id = (Connections.port_from_id)
但必须是:
LEFT JOIN connections Connections ON Ports.id = (Connections.port_from_id) OR Ports.id = (Connections.port_to_id)
或类似的东西。
我的 Ports-Model 实际上是这样的:
$this->hasOne('Connections', [
'foreignKey' => 'port_from_id',
'joinType' => 'LEFT'
]);
如何在我的连接中获取 OR 条件?
谢谢!
您必须禁用关联外键处理(IIRC 这仅适用于使用 JOIN
策略的 hasOne
关联,它 可能 有效对于 belongsTo
也是如此),并自行提供条件,因为不支持多个外键(与复合外键不同)。
大致如下:
use Cake\Database\Expression\IdentifierExpression;
// ...
$this->hasOne('Connections', [
'foreignKey' => false,
'conditions' => [
'OR' => [
'Connections.port_from_id' => new IdentifierExpression($this->aliasField('id')),
'Connections.port_to_id' => new IdentifierExpression($this->aliasField('id')),
]
]
]);
这应该创建 SQL 类似于:
LEFT JOIN
`connections` `Connections` ON (
`Connections`.`port_from_id` = (`Ports`.`id`) OR
`Connections`.`port_to_id` = (`Ports`.`id`)
)
另见
我正在尝试从另一个 table(端口)两次加入 table(连接)。
条件是:
- 一个端口可以有一个或没有连接
- 一个连接有一个从端口和一个到端口
结构是:
Table 端口:
- id
- 人数
Table 连接数:
- id
- port_from_id
- port_to_id
- 名字
所以现在我想从 Ports 加入 Connections。
蛋糕总是给我这个:
LEFT JOIN connections Connections ON Ports.id = (Connections.port_from_id)
但必须是:
LEFT JOIN connections Connections ON Ports.id = (Connections.port_from_id) OR Ports.id = (Connections.port_to_id)
或类似的东西。
我的 Ports-Model 实际上是这样的:
$this->hasOne('Connections', [
'foreignKey' => 'port_from_id',
'joinType' => 'LEFT'
]);
如何在我的连接中获取 OR 条件?
谢谢!
您必须禁用关联外键处理(IIRC 这仅适用于使用 JOIN
策略的 hasOne
关联,它 可能 有效对于 belongsTo
也是如此),并自行提供条件,因为不支持多个外键(与复合外键不同)。
大致如下:
use Cake\Database\Expression\IdentifierExpression;
// ...
$this->hasOne('Connections', [
'foreignKey' => false,
'conditions' => [
'OR' => [
'Connections.port_from_id' => new IdentifierExpression($this->aliasField('id')),
'Connections.port_to_id' => new IdentifierExpression($this->aliasField('id')),
]
]
]);
这应该创建 SQL 类似于:
LEFT JOIN
`connections` `Connections` ON (
`Connections`.`port_from_id` = (`Ports`.`id`) OR
`Connections`.`port_to_id` = (`Ports`.`id`)
)
另见