在我的客户模型中,我想总结每个付款状态成功的所有交易,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
答案 0 :(得分: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)