【问题标题】:How to custom order by enum and other columns如何按枚举和其他列自定义顺序
【发布时间】:2019-07-23 15:25:07
【问题描述】:

我正在尝试按两列排序。第一列是枚举字段(状态),第二列是 updated_at 列。

我目前是按枚举排序,如下图:

Car.order("
  (status = 1 DESC, updated_at DESC),
   status = 2 DESC,
   status = 3 DESC,
   status = 4 DESC,
   status = 5 DESC,
   status = 6 DESC,
   status = 7 DESC"
)

如果有 3 辆汽车的状态为 1,我希望这 3 辆汽车通过 updated_at 列降序排序。

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-5.2


    【解决方案1】:

    根据评论。

    可以将SQL语句的ORDER BY传递给order查询方法:

    Car.order(
      'status DESC,
       updated_at DESC,
       CASE WHEN status = 7 THEN 0
            WHEN status = 4 THEN 1
            ...
            END'
    )
    

    【讨论】:

    • 这适用于上面的示例,但如果我也更改状态顺序,我希望它也能正常工作。例如,如果我希望状态顺序为 (1,3,5,2,4,7)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    相关资源
    最近更新 更多