本文介紹了Eloquent 中的 MySQL 按字段排序的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
當我想在 MySQL 查詢中定義自定義排序順序時,我可以這樣做:
When I want to define a custom sort order in a MySQL query I can do something like this:
ORDER BY FIELD(language,'USD','EUR','JPN')
Eloquent ORM 版本是什么?
What would be the Eloquent ORM version of that?
更新:
這是解決方案,它也適用于在各個領域進行排序:
This is the solution and it also works when ordering on various fields:
$events = Event::with( 'type', 'location' )
->orderBy( 'event_type_id' )
->orderByRaw( "FIELD(status, 'good', 'bad', 'hidden', 'active', 'cancelled')" )
->orderBy( 'date' );
推薦答案
直接使用 DB::raw()
或 orderByRaw
應該可以:
Using either DB::raw()
or orderByRaw
directly should work:
$models = Model::orderByRaw('FIELD(language, "USD", "EUR", "JPN")')->get();
// or
$models = Model::orderBy(DB::raw('FIELD(language, "USD", "EUR", "JPN")'))->get();
這篇關于Eloquent 中的 MySQL 按字段排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!