【问题标题】:ActiveRecord Group and Count - Where Does count_id Come From?ActiveRecord 组和计数 - count_id 来自哪里?
【发布时间】:2015-02-23 21:13:27
【问题描述】:

我有OrderItem 模型加入了OrderItem

class OrderItem < ActiveRecord::Base
  belongs_to :order
  belongs_to :item

此查询查找最热门商品的 ID:

OrderItem.group(:item_id).order("count_id DESC").count("id").first(10).map(&:first)

这可行,但count_id 是什么?为什么这行得通? order("count_id... 幕后发生了什么?

【问题讨论】:

    标签: activerecord


    【解决方案1】:

    count_id 是 Rails 赋予 SQL 聚合函数 COUNT("order_items"."id") 的别名。

    OrderItem.group(:item_id).count(:id) 计算每个单独项目的行数:

    SELECT COUNT("order_items"."id") AS count_id, item_id AS item_id FROM "order_items"  GROUP BY item_id
    

    count_id 部分背后的魔力在于ActiveRecord::Calculations。别名在这里确定:

    aggregate_alias = column_alias_for([operation, column_name].join(' '))
    

    column_alias_for 列表的方法 cmets 显示了这个例子:

    #   column_alias_for("count", "id")              # => "count_id"
    

    之后,order 按从大到小列出 Item 出现的次数。返回值将是一个哈希值,其中键是项目 ID,值是出现次数。

    first 抓取出现次数最多的 10 个项目,map 提取 item_id 值。

    【讨论】:

      猜你喜欢
      • 2010-09-21
      • 1970-01-01
      • 2020-12-26
      • 2022-09-17
      • 1970-01-01
      • 2012-11-20
      • 1970-01-01
      • 1970-01-01
      • 2014-04-24
      相关资源
      最近更新 更多