【问题标题】:How to create a hasOne association that joins on multiple foreign keys via an OR condition?如何创建通过 OR 条件连接多个外键的 hasOne 关联?
【发布时间】:2018-02-23 15:48:39
【问题描述】:

我正在尝试从另一个表(端口)加入一个表(连接)两次。

条件是:

  • 一个端口可以有一个或没有连接
  • 一个连接有一个从端口和一个到端口

结构是:

表端口:

  • 身份证
  • 号码

表连接:

  • 身份证
  • port_from_id
  • port_to_id
  • 姓名

所以现在我想从端口加入连接。

蛋糕总是给我这个:

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-Condition?

谢谢!

【问题讨论】:

    标签: php cakephp join foreign-keys cakephp-3.x


    【解决方案1】:

    您必须禁用关联外键处理(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`)
        )
    

    另见

    【讨论】:

    • 这是我要求的 100%。非常感谢你!因此,我尝试使用 cakephp-documentation 重建您的解决方案。但它没有解释海事组织。所以我自己不会找到答案:-/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多