[英]MySQL ordering by grouped date ranges
I have a model with the following four scopes: 我有一个具有以下四个范围的模型:
scope :active, -> { where("start_at <= '#{Time.now.utc}' AND end_at > '#{Time.now.utc}'") }
scope :ended, -> { where("end_at < '#{Time.now.utc}'") }
scope :coming_soon, -> { where("start_at > '#{Time.now.utc}' AND start_at < '#{Time.now.utc+6.hours}'") }
I want to be able to do something like (pseudocode, just trying to give an idea): 我希望能够做类似的事情(伪代码,只是试图给出一个想法):
Model.all.order(active, coming_soon, ended)
The result would be all rows from that table, sorted by rows meeting the active
constraints first, followed by the ones meeting the coming_soon
constraint, and finally all the ones meeting the ended
constraints. 结果将是该表中的所有行,
coming_soon
先满足active
约束的行排序,然后再满足coming_soon
约束的行排序,最后再满足ended
约束的所有行排序。
I added the following scope and it seems to have solved my problem: 我添加了以下范围,它似乎已经解决了我的问题:
scope :time_sorted, -> {
select("events.*, CASE
WHEN start_at <= '#{Time.now.utc}' AND end_at > '#{Time.now.utc}' THEN 1
WHEN end_at < '#{Time.now.utc}' THEN 2
WHEN start_at > '#{Time.now.utc}' AND start_at < '#{Time.now.utc+6.hours}' THEN 3 ELSE 4
END AS formula")
.order("formula ASC")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.