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?
Use order by like this: return User::orderBy('name', 'DESC') ->orderBy('surname', 'DESC') ->orderBy('email', 'DESC') ... ->get(); Hope it works!!
The Laravel Orderby works by simply sorting the results of the query. So if the column has a list of 20 data, it can sort the list by the parameter provided. One can also create an order in an ascending or a Descending Order.
get method give a collection and first method give you a model instance. When you want to get collection of data means, lots of results then use get but if you want to retrieve only one result then use first.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With