【问题标题】:MySQL order by field in Eloquent在 Eloquent 中按字段排序 MySQL
【发布时间】:2015-06-21 22:58:21
【问题描述】:

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

【问题讨论】:

  • 你试过$query->orderBy("FIELD(language,'USD','EUR','JPN')", 'asc');吗?
  • 是的,但这会导致“未知字段”错误。

标签: php mysql sql eloquent


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    直接使用DB::raw()orderByRaw 应该可以:

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

    【讨论】:

    • 除了原始订单查询之外,我还在其他字段上订购。所以我现在得到这个错误:SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'asc' at line 1 (SQL: select * from `events` where `events`.`deleted_at` is null and `status` = 'good' order by `event_type_id` asc, FIELD(status, 'good', 'bad', 'hidden', 'active', 'cancelled', `date` asc)
    • 看起来你把asc放在括号内
    • 我更新了最初的问题以包含 Eloquent 语法。
    • 对不起,我的错。好像我忘了添加右括号。感谢您的回答。现在可以使用了。
    • 不用担心。很高兴我能帮忙:)
    猜你喜欢
    • 2020-09-05
    • 2018-06-27
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多