0

问题:

在我的客户模型中,我想总结每次付款状态成功的所有交易,并且customer_id匹配当前实例的 id 或当前实例的parent_id. 首先,我根本无法让它工作,因为我试图在一个查询中完成所有操作。现在我有了我要找的东西,但恐怕我的效率还不够高。

语境:

  • 事务表有一customer_id
  • 客户表有一parent_id列。
  • 客户类has_many :transactions
  • 交易类belongs_to :customer
  • 交易类has_many :payments

这是我的模型:

class Customer < ActiveRecord::Base
  has_many :transactions
end

class Transaction < ActiveRecord::Base
  belongs_to :customer
  has_many :payments
end

class Payment < ActiveRecord::Base
  has_one :transaction
end

问题:

如果这是我目前使用的模型属性,我该如何提高它的性能,如果有的话?

def total_spent
  if customer_type == 1 # "child" customer
    Transaction.joins(:payments).where('payments.status' => 3).sum(:amount, :conditions => ['customer_id = ?', id])
  elsif customer_type == 2 # "parent" customer
    temp_transactions = Transaction.joins(:payments).where('payments.status' => 3)
    temp = temp_transactions.sum(:amount, :conditions => ['customer_id = ?', id])
    Customer.find_all_by_parent_group_id(id).each do |c|
      temp = temp + temp_transactions.sum(:amount, :conditions => ['customer_id = ?', c.id])
    end
    temp
  end
end
4

1 回答 1

1
Transaction.joins(:payments)
   .joins(:customer)
   .where(:payments => {:status => 3})
   .where("customers.id = ? or customers.parent_id = ?", 5, 5)
   .sum(:amount)


SELECT SUM(amount) AS sum_id 
FROM "transactions" 
    INNER JOIN "payments" ON "payments"."transaction_id" = "transactions"."id" 
    INNER JOIN "customers" ON "customers"."id" = "transactions"."customer_id" 
WHERE 
   "payments"."status" = 3 
   AND (customers.id = 5 or customers.parent_id = 5)
于 2013-02-23T02:37:03.303 回答