ActiveRecord组和计数-count_id来自何处? [英] ActiveRecord Group and Count - Where Does count_id Come From?
问题描述
我有 Order
和 Item
模型,还有 OrderItem
:
class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :item
此查询最受欢迎商品的ID:
This query finds the IDs of the most popular items:
OrderItem.group(:item_id).order("count_id DESC").count("id").first(10).map(&:first)
这有效,但什么是 count_id
?为什么这样做? order( count_id ...
)在幕后发生了什么?
This works, but what is count_id
? Why does this work? What is going on here behind the scenes with order("count_id...
?
推荐答案
count_id
是Rails赋予SQL聚合函数 COUNT( order_items。 id)$ c的别名$ c>。
count_id
is an alias that Rails gives to the SQL aggregate function COUNT("order_items"."id")
.
OrderItem.group(:item_id).count(:id)
计算行数对于每个单个项目:
OrderItem.group(:item_id).count(:id)
counts the number of rows for each individual item:
SELECT COUNT("order_items"."id") AS count_id, item_id AS item_id FROM "order_items" GROUP BY item_id
count_id
背后的魔力部分在 ActiveRecord中: :计算
。别名在此处确定:
The magic behind the count_id
part is in ActiveRecord::Calculations
. The alias is determined here:
aggregate_alias = column_alias_for([operation, column_name].join(' '))
的方法注释column_alias_for
列表显示此示例:
# column_alias_for("count", "id") # => "count_id"
之后,订单
列出项目出现的次数从大到小。返回值将是一个哈希值,其中键是项ID,值是出现次数。
After that, order
lists the Item occurrences from largest to smallest. The return value will be a hash where the keys are Item IDs and the values are the count of occurrences.
第一
抓取出现次数最多的10个项目,然后 map
提取 item_id
值。
first
grabs the 10 items with the most occurrences, and map
pulls out the item_id
values.
这篇关于ActiveRecord组和计数-count_id来自何处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!