MySQL在Eloquent中按字段排序

时间:2015-04-15 19:44:32

标签: php mysql sql eloquent

当我想在MySQL查询中定义自定义排序顺序时,我可以这样做:

ORDER BY FIELD(language,'USD','EUR','JPN')

那个雄辩的ORM版本是什么?

更新

这是解决方案,在各种领域订购时也适用:

$events = Event::with( 'type', 'location' )
               ->orderBy( 'event_type_id' )
               ->orderByRaw( "FIELD(status, 'good', 'bad', 'hidden', 'active', 'cancelled')" )
               ->orderBy( 'date' );

2 个答案:

答案 0 :(得分:20)

直接使用DB::raw()orderByRaw应该有效:

$models = Model::orderByRaw('FIELD(language, "USD", "EUR", "JPN")')->get();
// or
$models = Model::orderBy(DB::raw('FIELD(language, "USD", "EUR", "JPN")'))->get();

答案 1 :(得分:1)

在FIELD()的第二个参数中使用内爆

 $facilities = $query->with(['interest','city:id,name', 'state:id,name'])
        ->Active()
        ->whereIn('facility_id', $facilities_list)
        ->orderByRaw('FIELD(facility_id, '.implode(", " , $facilities_list).')')
        ->get();