我有一个模型让我们说Post
有一个名为published_at
的列(日期时间)。我的模型有两个名为next
和prev
的实例方法。
我正在使用mysql作为数据库适配器。
def next
self.class.unscope(:order).online
.where('published_at > ?', published_at)
.order('published_at ASC').first
end
def prev
self.class.unscope(:order).online
.where('published_at < ?', published_at)
.order('published_at DESC').first
end
使用上面的代码,如果每个帖子都有另一个日期,导航将起作用。如果某些帖子在同一天,则会显示其中一条记录。
目标:获取按published_at
日期时间列排序的下一个或上一个记录。
有什么想法吗?
答案 0 :(得分:1)
&#34; next&#34; ,&#34;之前的&#34; 在SQL中都没有意义。您必须显式通过 uniq 键定义排序顺序。
如果您将非uniq列作为排序基础,则必须添加uniq one,例如id
。
然后你必须改变WHERE子句以接受非uniq列具有相同值的行:
def next
condition = <<~SQL
(published_at = :published_at AND id > :id) OR
(published_at > :published_at)
SQL
self.class.unscope(:order).
online.
where(condition, published_at: published_at, id: id).
order(published_at: :asc, id: :asc).
take
end
prev
构建类似。