Rails 4 + ActiveRecord + postgresql + group by 不行吗?

Rails 4 + ActiveRecord + postgresql + group by do not work?

我想通过 ActiveRecord 进行以下查询,但我不能。

SELECT
  catalog_product_id,
  COUNT (catalog_product_id)
FROM
  sc_items
WHERE sc_items.shopping_cart_id = 34
GROUP BY
  catalog_product_id;
BEGIN

Table: 
scItems(catalog_product_id, shopping_cart_id)
[1,1]
[2,1]
[2,1]
[2,1]

我正在执行以下代码 ruby 代码:

sc_items.select("catalog_product_id, count(catalog_product_id) as count").group("catalog_product_id")

生成这个sql:

SELECT catalog_product_id, count(catalog_product_id) as count FROM "sc_items" WHERE "sc_items"."shopping_cart_id" =  GROUP BY catalog_product_id  [["shopping_cart_id", 34]]

我得到了这个结果:

#<ActiveRecord::AssociationRelation [#<ScItem id: nil, catalog_product_id: 1>, #<ScItem id: nil, catalog_product_id: 3>]> 

另一方面,如果我执行上面的 sql:

res = ActiveRecord::Base.connection.execute(sql)
res.class
res.to_a

我明白了:

#<PG::Result:0x007fcb3720bea8 status=PGRES_TUPLES_OK ntuples=2 nfields=2 cmd_tuples=2> 
PG::Result 
[{"catalog_product_id"=>"2", "count"=>"3"}, {"catalog_product_id"=>"1", "count"=>"1"}] 

这是正确的结果,如何使用 ActiveRecord 进行此查询?。如果 sql 相同,为什么 activeRecord 缺少 catalog_product_id 的 id?

附加信息:

我相信你有一个名为 ScItem 的模型

ScItem.where(shopping_cart_id: 34).group(:catalog_product_id).count

您可以找到有关分组依据和计数的更多详细信息here

根据我使用的某些属性对整个 table 进行分组

ScItem.unscoped.group(:catalog_product_id).count