带有CASE WHEN THEN ELSE条件的CakePHP查询

时间:2019-04-02 13:43:55

标签: cakephp cakephp-3.0

SELECT CASE WHEN a.type = 'property' THEN p.name ELSE r.name END AS `name`, a.*
FROM admin_alert a
LEFT JOIN  property p ON a.related_id = p.id 
LEFT JOIN  publisher r ON a.related_id = r.id 

如何在CakePHP中编写此sql?

1 个答案:

答案 0 :(得分:0)

$AdminAlerts = TableRegistry::get('AdminAlert')->find();

    $AdminAlerts = $AdminAlerts->join([
        'table' => 'property',
        'alias' => 'pr',
        'type' => 'LEFT',
        'conditions' => 'related_id = pr.id AND type = "property"',
    ]);
    $AdminAlerts = $AdminAlerts->join([
        'table' => 'publisher',
        'alias' => 'pu',
        'type' => 'LEFT',
        'conditions' => 'related_id = pu.id AND type = "publisher"',
    ]);

    $relatedName = $AdminAlerts->newExpr()
            ->addCase(
                [$AdminAlerts->newExpr()->add(['type' => 'property']),
                $AdminAlerts->newExpr()->add(['type' => 'publisher'])],

                [ new IdentifierExpression('pr.name'), new IdentifierExpression('pu.name')]

            );
    $AdminAlerts = $AdminAlerts->select(['id','related_id','type','title','message','name' => $relatedName]);

这有效