如何使用CakePHP 3在ORDER BY下实现CASE WHEN

时间:2017-10-31 09:53:00

标签: cakephp-3.0 cakephp-3.4

SQL:

SELECT Students.name AS `Students__name`, Students.role AS 
`Students__role` FROM students Students
WHERE id IN 
  (1053,1056,733,734,735,736,737,739,748) 
  AND name LIKE '%v%' ORDER BY 
CASE 
  WHEN name LIKE '%v' THEN 1
  WHEN name LIKE 'v%' THEN 2
  WHEN name LIKE '%v%' THEN 3
  ELSE 4
END

到目前为止:

$SInfo = TableRegistry::get('Students')->find()
->where(function($ex) use ($sArray, $sName) {
    $ex->in('id', $sArray);
    $ex->like('name', '%'.$sName.'%');
    return $ex;
});
->select(['name', 'role']);

order()函数不接受ExpressionQuery。我已尝试在订单下使用$ex->addCase(),但这也无效。

1 个答案:

答案 0 :(得分:2)

如果要在order()方法中使用CASE语句,可以这样写:

$SInfo = TableRegistry::get('Students')->find()
    ->select(['name', 'role'])
    ->where(function($ex) use ($sArray, $sName) {
        $ex->in('id', $sArray);
        $ex->like('name', '%' . $sName . '%');
        return $ex; 
    })
    ->order('(CASE WHEN name LIKE \'%v\' then 1 when name LIKE \'v%\' then 2 when name LIKE \'%v%\' then 3 else 4 END)');

编辑:正如在这个答案的评论中所建议的那样(感谢@ndm)你应该使用相应的CASE表达式:

$SInfo = TableRegistry::get('Students')->find()
->select(['name', 'role'])
->where(function($ex) use ($sArray, $sName) {
    $ex->in('id', $sArray);
    $ex->like('name', '%' . $sName . '%');
    return $ex; 
})
->order(function ($exp, $q) {
    return $exp->addCase(
        [
            $q->newExpr()->like('name', '%v'),
            $q->newExpr()->like('name', 'v%'),
            $q->newExpr()->like('name', '%v%'),
        ],
        [1,  2, 3, 4], # values matching conditions
        ['integer', 'integer', 'integer', 'integer'] # type of each value
    );
});