Home > Blockchain >  Eloquent : Order query result by number of null values
Eloquent : Order query result by number of null values

Time:09-27

I have a working query like that :

$users = User::whereNotNull('name')orWhereNotNull('phone')orWhereNotNull(email)->get()

My database datas look like that

id | name | phone | email
1  | Luc  | null  | null
2  | Bob  | null  | [email protected]
3  | null | null  | null
4  | Bil  |  2121 | [email protected]

With my precious query it will return lines with id : 1, 2 and 3. But I want to order them by number of columns with null, which mean the users with the most null datas. In my example it will return in this order : 3, 1, 2

Is it possible to do it with eloquent? Like with a withCount() and orderBy() ?

CodePudding user response:

You can try this :

$users = User::whereNotNull('name')
           ->orWhereNotNull('phone')
           ->orWhereNotNull('email')
           ->orderByRaw('ISNULL(name)   ISNULL(phone)   ISNULL(email) DESC')
           ->get();
  • Related