MySQL 按 Eloquent 中的字段排序
MySQL order by field in Eloquent
当我想在 MySQL 查询中定义自定义排序顺序时,我可以这样做:
ORDER BY FIELD(language,'USD','EUR','JPN')
它的 Eloquent ORM 版本是什么?
更新:
这是解决方案,它也适用于在各个领域订购:
$events = Event::with( 'type', 'location' )
->orderBy( 'event_type_id' )
->orderByRaw( "FIELD(status, 'good', 'bad', 'hidden', 'active', 'cancelled')" )
->orderBy( 'date' );
直接使用 DB::raw()
或 orderByRaw
应该有效:
$models = Model::orderByRaw('FIELD(language, "USD", "EUR", "JPN")')->get();
// or
$models = Model::orderBy(DB::raw('FIELD(language, "USD", "EUR", "JPN")'))->get();
在FIELD()的第二个参数中使用implode
$facilities = $query->with(['interest','city:id,name', 'state:id,name'])
->Active()
->whereIn('facility_id', $facilities_list)
->orderByRaw('FIELD(facility_id, '.implode(", " , $facilities_list).')')
->get();
如果您正在使用联接,您可以简单地在列前添加 table 名称。
Student::orderByRaw('FIELD(students.id, 3, 2, 1) DESC')->join('students_contact', 'students_contact.student_id', '=', 'students.id')
->get();
注意:
开始在右侧的原始查询中添加一列,让我用一个例子来解释
如果要实现订单7,8,9
orderByRaw('FIELD(students.id, 9, 8, 7) DESC')
然后它会以正确的方式获取数据。我还添加了 DESC 关键字,因为它会在列表底部而不是列表开头添加排序数据。
当我想在 MySQL 查询中定义自定义排序顺序时,我可以这样做:
ORDER BY FIELD(language,'USD','EUR','JPN')
它的 Eloquent ORM 版本是什么?
更新:
这是解决方案,它也适用于在各个领域订购:
$events = Event::with( 'type', 'location' )
->orderBy( 'event_type_id' )
->orderByRaw( "FIELD(status, 'good', 'bad', 'hidden', 'active', 'cancelled')" )
->orderBy( 'date' );
直接使用 DB::raw()
或 orderByRaw
应该有效:
$models = Model::orderByRaw('FIELD(language, "USD", "EUR", "JPN")')->get();
// or
$models = Model::orderBy(DB::raw('FIELD(language, "USD", "EUR", "JPN")'))->get();
在FIELD()的第二个参数中使用implode
$facilities = $query->with(['interest','city:id,name', 'state:id,name'])
->Active()
->whereIn('facility_id', $facilities_list)
->orderByRaw('FIELD(facility_id, '.implode(", " , $facilities_list).')')
->get();
如果您正在使用联接,您可以简单地在列前添加 table 名称。
Student::orderByRaw('FIELD(students.id, 3, 2, 1) DESC')->join('students_contact', 'students_contact.student_id', '=', 'students.id')
->get();
注意: 开始在右侧的原始查询中添加一列,让我用一个例子来解释 如果要实现订单7,8,9
orderByRaw('FIELD(students.id, 9, 8, 7) DESC')
然后它会以正确的方式获取数据。我还添加了 DESC 关键字,因为它会在列表底部而不是列表开头添加排序数据。