How to use order by in Laravel when it uses CASE WHEN?

 ̄綄美尐妖づ 提交于 2021-02-07 13:58:18

问题


I can use orderBy method in Laravel like this:

$posts = Post::orderBy('id', 'DESC')->get();

Ok, what about when there is CASE in the ORDER BY clause? Like this:

ORDER BY 
CASE
   WHEN id.PinRequestCount <> 0 THEN 5
   WHEN id.HighCallAlertCount <> 0 THEN 4
   WHEN id.HighAlertCount <> 0 THEN 3
   WHEN id.MediumCallAlertCount <> 0 THEN 2
   WHEN id.MediumAlertCount <> 0 THEN 1
END desc,

How can I write this ^ in Laravel?


回答1:


Try this:

->orderByRaw(
     "CASE WHEN <CONDITION> THEN < > ELSE < > END DESC"
)



回答2:


You are to use raw, as sagi has also mentioned.

$posts = Post::select(DB::raw
('CASE
   WHEN id.PinRequestCount <> 0 THEN 5
   WHEN id.HighCallAlertCount <> 0 THEN 4
   WHEN id.HighAlertCount <> 0 THEN 3
   WHEN id.MediumCallAlertCount <> 0 THEN 2
   WHEN id.MediumAlertCount <> 0 THEN 1
END desc')
)->orderBy('id', 'DESC')->get();


来源:https://stackoverflow.com/questions/39941003/how-to-use-order-by-in-laravel-when-it-uses-case-when

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!