我正在使用has_ancentry gem,我希望类别计数是这种格式
“技术/笔记本电脑(50)”
其中“技术”是父类别。 “笔记本电脑”是子类别,“50”是我的分组查询的计数
categories = Category.joins(:products)
.where(products: {id: @products})
.group(:id, :name)
.count
问题是,通过这种方式,我只获得了儿童类别的“ID”。如果我要检索“父”类别,我必须拥有活动记录对象(因为在has_ancestry .parent()中是方法对象而不是数据库列)
模型
class Category < ApplicationRecord
has_ancestry
has_many :products, dependent: :destroy
分类
create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "ancestry"
t.index ["ancestry"], name: "index_categories_on_ancestry"
end
我对解决问题有些困惑。
但我有一些解决方案。
ancestry gem不支持关联的查询接口
所以我用
脏的方式:它导致n + 1查询问题
Category.joins(:products).where(products: {id: @products}).group(:id, :name).count
.map { |k, v| "#{Category.find(k.first).parent.name} / #{k.last} (#{v})" }
简短的方法:它导致n + 1查询问题
Product.group(:category).size.map { |k, v| "#{k.parent.name} / #{k.name} (#{v})" }
简短的方法2:它导致n + 1查询问题
Category.includes(:products).map { |c| [c.parent&.name, c.name, c.products.size]}
我想使用原始查询,但我目前无法想到一个好的SQL,对不起,
更新新的:
products = Product.group(:category).size
categories = Category.where(id: products.map(&:first).map(&:ancestry).uniq).pluck(:id, :name)
result = products.map { |child_category, total| "#{(categories.select { |c| c.first == child_category.ancestry.to_i }.map(&:last)).first} / #{child_category.name} (#{total})" }
这看起来有点复杂,但只有两个查询。
它需要您的机器更多的计算能力。