对订单中的商品进行分组和计数

pzi*_*zin 9 postgresql activerecord ruby-on-rails

我有这三个模型:

class Order
  has_many :items
end

class Item
  belongs_to :order
  belongs_to :product
end

class Product
  has_many :orders, through: :items
  has_many :items
end
Run Code Online (Sandbox Code Playgroud)

我需要列出给定日期范围内订单中每种产品的数量.

我有一个范围来获取日期范围内的所有订单:

Order.date_range(from, to)
Run Code Online (Sandbox Code Playgroud)

现在我需要分组和数数; 项目模型上有字段product_idunits字段.

我见过解决方案,但只有两个表(订单>产品)而不是三个(订单>商品>产品).

Tom*_*Tom 4

您可以将关系添加has_many :products, through: :items到订单模型。

然后Order.date_range(from, to).joins(:products).group(:product_id).count(你也可以这样做group('products.id')

如果该items.units列并不总是 1 并且需要求和,您可以执行以下操作:Order.date_range(from, to).joins(:products).group(:product_id).sum(:units)

返回值将分别是订单中每个产品的{product1.id => count(product1.id), ...}或 的哈希值。{product1.id => sum(units1), ...}