0

我正在使用 rails 3.2,并尝试使用 ActiveRecord 来查询我的数据库。我有 2 个 activerecord 模型,Admin 和 Order:

class Admin < ActiveRecord::Base
  attr_accessible :email, :name
  has_many :orders
class Order < ActiveRecord::Base
  attr_accessible :operation
  belongs_to :admin

在我的例子中,order.operation 是一个字符串,代表订单类型。我正在尝试构建一个给我三列的查询:

admin.name, admin.orders.where(:operation => 'bonus').count, admin.orders.where(:operation => 'gift').count

有没有办法把它放在一个查询中?

编辑:这是原始 sql 来获得我需要的东西:

SELECT t_a.admin_id_com, t_a.name, gb_f_f_gb_f_fi.bonus_count, gb_f_f_gb_f_fi.gifts_count 
FROM (
  SELECT f_fil.admin_id_gifts, f_fil.gifts_count, f_filt.admin_id_bonus, f_filt.bonus_count 
  FROM (
    SELECT admin_id as admin_id_gifts, count(distinct id) as gifts_count FROM orders WHERE operation = 'new gifts!' GROUP BY admin_id_gifts) 
  f_fil LEFT OUTER JOIN (
    SELECT admin_id as admin_id_bonus, count(distinct id) as bonus_count FROM orders WHERE operation = 'new bonuses!' GROUP BY admin_id_bonus) 
  f_filt ON (f_fil.admin_id_gifts = f_filt.admin_id_bonus)) 
gb_f_f_gb_f_fi LEFT OUTER JOIN (
  SELECT id AS admin_id_com, t_ad.name FROM admins t_ad) t_a ON (gb_f_f_gb_f_fi.admin_id_gifts = t_a.admin_id_com)

是否可以使用 ActiveRecord 构建这样的查询?

4

1 回答 1

1

尝试这个:

@admins   = Admin.joins(:orders).
                 select("admins.id, admins.name, orders.id, 
                          SUM((orders.operation = 'bonus')::integer) AS bonus_count, 
                          SUM((orders.operation = 'gift')::integer) AS gift_count ").
                 group("admins.id ")

# access each columns as
admin.name, admin.bonus_count, admin.gift_count

其他选项是使用急切加载,它将使用两个查询但可能更快

@admins  = Admin.includes(:orders)

# in admin.rb
def orders_count(type)
  # Don't use where here as it would make a separate query instead of using eager loading records
   orders.select{|x| x.operation == type}.count
end 

# access each columns as
admin.name, admin.orders_count("bonus"), admin.orders_count("gift")
于 2013-10-04T16:08:38.607 回答