当我想在 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模板网!