【问题标题】:Rails use Model method in a group queryRails 在组查询中使用 Model 方法
【发布时间】:2019-03-24 16:04:42
【问题描述】:

我正在使用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

【问题讨论】:

  • 请更新您的帖子,包括模型和关联。我们需要更多信息来解决问题,
  • 完成。我添加了类别模型。
  • 请添加实际架构而不仅仅是模型,因为最终您应该有某种 id 来获取子产品
  • 完成。这是一个经典的 has_ancestry 表

标签: ruby-on-rails activerecord ruby-on-rails-5 rails-activerecord


【解决方案1】:

我对理解一个问题有些困惑。

但我有一些解决方案。

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})" }

short way:导致n+1查询问题

Product.group(:category).size.map { |k, v| "#{k.parent.name} / #{k.name} (#{v})" }

short way2:导致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})" }

这看起来有些复杂,但只有两个查询。

你的机器需要更多的计算能力。

【讨论】:

  • 是的,我可以出售导致 N+1 查询的问题。我会在不引起 n+1 查询的情况下这样做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多