5

I've been looking like crazy but I can't seem to find a way of achieving something similar to this with Laravel's Eloquent:

select id,name 
from friends 
order by id=5 desc

Example taken from the following link: mysql SQL: specific item to be first and then to sort the rest of the items

I was hoping a simple Group::orderBy('id', $id, 'DESC')->get() would work, but no such luck.

I've also looked into using DB instead but the orderBy method for that class takes in exactly the same arguments and doesn't have an option for specific IDs. Are there any alternatives?

Thank you very much for all the help!

Community
  • 1
  • 1
adamj
  • 4,672
  • 5
  • 49
  • 60
  • @azngunit81 The SQL is not mine it's from the link shown just below it. I've tested the above SQL `order by` on my own table ordering by `id` 6 and `DESC` and it worked very nicely. Here is screenshot of it working: http://imgur.com/I5um7YL – adamj Jul 01 '14 at 04:42

1 Answers1

9

not sure , but may be you could try using orderByRaw(), like,

$id = 5;
Group::orderByRaw(DB::raw("FIELD(id, $id)"))
       ->get();
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
  • 2
    Mate I freakin' owe you one! How in the world did you find `orderByRaw`? It's not listed on their website at all, or I must be seriously blind. I changed your code slightly as `DB::raw` didn't quiet work as expected, here is my working code: `Group::orderByRaw("id = $user_group_id DESC")->get();` – adamj Jul 01 '14 at 04:51
  • 2
    @adamj glad you figured it out. It's not documented, but was added to 4.0.8 version of Laravel.. http://wiki.laravel.io/Changelog_%28Laravel_4%29 :) – Sudhir Bastakoti Jul 01 '14 at 05:28
  • 1
    You're helping out a guy in 2021, seven years after this post, first result on google btw. Thanks for pointing out your solution, `DB::raw("FIELD...` didn't work for me either. @adamj – AlexioVay Aug 02 '21 at 19:47