gpt4 book ai didi

sql - Rails 中的 HABTM 关联 : collecting and counting the categories of a model's children

转载 作者:行者123 更新时间:2023-12-02 04:21:29 25 4
gpt4 key购买 nike

我有一个 has_and_belongs_to_many 关系设置。它看起来像这样:

  • 图书 have_and_belong_to_many 个类别
  • 类别have_and_belongs_to_many书籍
  • 商店有_many本书
  • 一本书属于一家商店

我试图显示每个商店中有多少本书属于每个类别。所以我的 View 会显示 Store X 有 200 本书,其中 80 本书是推理小说,60 本书是非小说类书籍,等等。

我一直在尝试多种不同的方法来做到这一点,但到目前为止还没有成功。我想我是从错误的地方开始的。任何方向将不胜感激。

谢谢

顺便说一句,这是 Rails 4 和 psql。

最佳答案

如果您有一个 books_categories 连接表,您可以添加一个 has_many :categories,通过: :books 关联,将 stores 链接到类别书籍

class Store < ActiveRecord::Base
has_many :books
has_many :categories, through: :books
end

这是最简单的部分。现在让我们获取每个类别和书籍数量(修订后):

def books_per_category
categories.select('categories.id, categories.name, count(books.id) as count')
.group('categories.id, categories.name')
.map do |c|
{
name: c.name,
count: c.count
}
end
end

@jakub-kosiński 提供

关于sql - Rails 中的 HABTM 关联 : collecting and counting the categories of a model's children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30130380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com