根据连接 table - Rails 对 postgres 中的行进行排序

Sorting rows in postgres based on joined table - Rails

我有以下情况

class Book
  has_many :book_publications
  has_many :publications, through: :book_publications
end

class BookPublication
  # book_id
  # publication_id
end

class Publication
  # date
end

Book1 | Publication1(2000)
Book1 | Publication2(2003)
Book2 | Publication3(2004)
Book2 | Publication4(1999)

我想根据首次出版日期对书籍进行排序,不关心其他日期。 因此,对于升序,我将拥有 Book2(1999)、Book1(2000) 和降序 Book1(2000)、Book2(1999)。以后的年份不应计算在此查询中。 基本上我需要找到每本书出版的第一年,以某种方式将其附加到查询中并以此为准。 我还需要仍然能够展示没有出版物的书籍。所以我无法进行连接以仅获取匹配的行。

class Book
  has_many :book_publications
  has_many :publications, through: :book_publications
  def self.order_by_publication_date
    left_joins(:publications)
      .group(:id)
      .order(Publication.arel_table[:date].minimum, :asc)
  end
end

如果您想要结果集中的日期,您可以select它:

class Book < ApplicationRecord
  has_many :book_publications
  has_many :publications, through: :book_publications

  def self.order_by_publication_date
    left_joins(:publications)
      .select(
        arel_table[Arel.star],
        Publication.arel_table[:date].minimum.as('publication_date')
      )
      .group(:id)
      .order(:publication_date, :asc)
  end
end