如何为IF .. ELSE构建Cakephp3 ORM查询?

时间:2018-01-08 17:38:21

标签: php sql cakephp-3.0

我是ORM概念的新手。请将以下查询构建为Cakphp3 ORM格式。

select sum(case when tr_type = 'credit' then awards else -awards end) as balance 
from user_orders where user_id = 12345;

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

    $query = $this->UserOrders->find()->where(['user_id' => 12345]);

             $awards = $query->newExpr()
                            ->addCase(
                                [
                                    $query->newExpr()->add(['tr_type' => 'credit'])
                                ],
                                [
                                    $query->newExpr()->add(['awards' => '-awards'])
                                ]);

$query->select(['balance' => $query->func()->sum($awards)]);

更多信息:https://book.cakephp.org/3.0/en/orm/query-builder.html#using-sql-functions

你可以看到Class File QueryExpresions.php,方法注释有太多的例子。