问题
I have this line of code which gets results from a database:
'clanMembers' => User::find(Auth::user() -> clan_id) -> where('clan_id', '=', Auth::user() -> clan_id) -> orderBy('username') -> get()
Currently it orders by the username. I wish to change this to order by the clan_rank field. This clan_rank field will only ever contain 3 different values. These are:
1. Owner
2. Admin
3. Member
I wish to have my results ordered with Owners first, then Admin, then members. How can I change my line of code to achieve these results?
回答1:
You need to use orderByRaw
:
instead of orderBy
part you should use
orderByRaw("FIELD(clan_rank , 'Owner', 'Admin', 'Member') ASC");
来源:https://stackoverflow.com/questions/26045934/laravel-ordering-results-by-specific-values