【问题标题】:Count and group records through three associations通过三个关联对记录进行计数和分组
【发布时间】:2013-10-24 10:46:54
【问题描述】:

我有三个模型:

  • 图书 [belongs_to :author]
  • 作者 [belongs_to :publisher, has_many :books]
  • 出版商 [has_many :authors]

我想知道每个出版商有多少本书,按出版商分组,并按拥有最多图书的出版商排序。我需要获得一个包含单个查询的列表,我可以在其中获得类似的内容:

  • 出版商 ABC:3800 本书
  • 出版商 XYZ:1922 本书
  • 出版商 JKL:192 本书
  • 等等

书籍属于作者,但不直接属于出版商——很难解释为什么。有没有简单的方法来实现这一点?

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    像这样使用has_many through 定义publisherbooks 之间的关系

    # publisher.rb
    
    has_many :books, :through => :authors
    

    然后你得到这样的有序计数

    records =  Publisher.joins(:books).
                         group("publishers.id").
                         select("publishers.*, COUNT(*) AS books_count").
                         order("books_count DESC")
    # => access book count as record.book_count
    

    如果您需要经常访问出版商的图书数量,请考虑在出版商表中添加一个名为books_count的列(以提高性能)。你可以使用counter cache更新它

    【讨论】:

    • 谢谢。效果很好。我想避免添加另一列并存储金额,但我会检查计数器缓存的事情。
    【解决方案2】:

    这应该可行:

    counts = Publisher.joins(:authors => :books).
                       select('publishers.id, count(books.id) as number').
                       group('publishers.id')
    # count[0] is now a Publisher object; and counts[0].number is the count of books they own
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 2011-04-21
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      相关资源
      最近更新 更多