繁体   English   中英

Laravel 使用 CASE WHEN 时如何使用 order by?

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

我可以像这样在 Laravel 中使用orderBy方法:

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

好的,当ORDER BY子句中有CASE时呢? 像这样:

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,

我怎样才能在 Laravel 中写这个 ^ ?

试试这个:

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

您将使用raw ,正如 sagi 也提到的。

$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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM