【问题标题】:Group and count products on items from orders对订单中的商品进行分组和计数
【发布时间】:2019-05-06 04:55:54
【问题描述】:

我有这三个模型:

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

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

我可以获取某个日期范围内的所有订单:

Order.date_range(from, to)

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

我已经看到了解决方案,但只是在有两个表(订单>产品)而不是三个(订单>项目>产品)的情况下。

【问题讨论】:

  • 你不能在 AREL 查找上调用 count 吗?这将在 sql 中执行并且应该是高性能的
  • 我不知道。由于一些 Rails 弃用警告,我刚刚使用了 Arel。
  • 对不起。我忘记了 arel 已合并到核心中。 arel 我的意思是 ActiveRecord_Relation 对象,即 Order.date_range(from, to).count
  • 我尝试使用连接、包含等。但无法使其工作。
  • 试试Item.joins(:order).where(orders: {created_at: @from..@to}).group(:product_id).pluck('items.product_id, sum(items.units)')或者请提供想要的结果。

标签: ruby-on-rails postgresql activerecord


【解决方案1】:

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

然后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), ...} 的哈希值。

【讨论】:

  • 两个答案都运行良好。我会接受这个,因为它感觉更像轨道方式并且速度更快(0.0897 vs 0.3538)。谢谢。
【解决方案2】:

在这种特殊情况下,您可以直接询问商品而不是订购订单,它可以简化事情,只使用 2 个而不是 3 个表。

Item.joins(:order).where(orders: {created_at: @from..@to}).group('product_id, category, code').pluck('items.product_id, sum(items.units)')

【讨论】:

    猜你喜欢
    • 2018-10-07
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2019-07-14
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    相关资源
    最近更新 更多