问题
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