【发布时间】:2016-04-13 14:48:42
【问题描述】:
我想通过 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" = $1 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呢?
附加信息:
- 'rails','4.2.0'
- 'pg', '~> 0.18.1'
- 红宝石'2.1.2'
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 activerecord group-by