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

How to implement CASE WHEN under ORDER BY using CakePHP 3

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(),但也没有用。

如果要在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
    );
});