Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mysql

laravel

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?

like image 865
stack Avatar asked Oct 09 '16 07:10

stack


People also ask

How to use 2 order by in Laravel?

Use order by like this: return User::orderBy('name', 'DESC') ->orderBy('surname', 'DESC') ->orderBy('email', 'DESC') ... ->get(); Hope it works!!

What is the use of orderBy in laravel?

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.

What is get and first in laravel?

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.


2 Answers

Try this:

->orderByRaw(
     "CASE WHEN <CONDITION> THEN < > ELSE < > END DESC"
)
like image 126
sagi Avatar answered Sep 27 '22 18:09

sagi


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();
like image 22
Sina Avatar answered Sep 27 '22 17:09

Sina