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?
Try this:
->orderByRaw(
"CASE WHEN <CONDITION> THEN < > ELSE < > END DESC"
)
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.