2
需要幫助,我有兩個型號理解一個軌的活動記錄查詢
客戶和交易
Customer
has_many :transactions
Transaction
belongs_to :customer
現在我需要讓所有的客戶比1個交易
- 更在過去30天
- 剛剛在過去30天內的1筆交易
需要幫助,我有兩個型號理解一個軌的活動記錄查詢
客戶和交易
Customer
has_many :transactions
Transaction
belongs_to :customer
現在我需要讓所有的客戶比1個交易
擴展在ScottJShea的答案,我會使用一些範圍
scope :one_recent_transaction, :conditions => lambda {
includes(:transactions).where("transactions.date > ?", DateTime.now - 30.days).group("customer.id").having("COUNT(transactions.id) = 1")
}
scope :many_recent_transactions, :conditions => lambda {
includes(:transactions).where("transactions.date > ?", DateTime.now - 30.days).group("customer.id").having("COUNT(transactions.id) > 1")
}
然後用它們這樣
one_transaction = Customer.one_recent_transaction
many_transactions = Customer.many_recent_transactions
您想使用HAVING
子句。我建議(我猜測有點不完全知道你的模型):
@exactly_one = Customer.where("transaction_date between ? and >", Date.now, Date.now - 30).group("customer.id").having("count(transaction.id) = 1")
@exactly_one = Customer.where("transaction_date between ? and >", Date.now, Date.now - 30).group("customer.id").having("count(transaction.id) > 1")
嗨Mohit你是什麼意思?您想限制客戶可以創建的交易數量爲1嗎? – blawzoo 2012-03-19 23:17:29
@blawzoo no。我想找出那些在過去30天內只有1筆交易的客戶。 – 2012-03-19 23:20:36
另外我需要找出那些在過去30天內有超過1筆交易的客戶。 – 2012-03-19 23:21:07