Eloquent 中的 MySQL 按字段排序

2021-12-26 00:00:00 sql php mysql eloquent

当我想在 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();

相关文章