[英]MySQL / Ruby on Rails - How to “SUM” in a :has_many case
I have the following tables: 我有以下表格:
User :has_many Purchases 用户:has_many购买
Item :has_many Purchases 项目:有许多购买
Item has a column "amount" (can be + or -) and I need to find all Users that have a positive SUM of "Item.amounts" (over all Purchases each one has made). 物料具有“金额”列(可以是+或-),我需要找到所有具有“ SOM.amounts”的正SUM的所有用户(在每个人进行的所有购买中)。
How does this query look like? 这个查询看起来如何? (I'm not sure how to handle "SUM" correctly, in this case.) (在这种情况下,我不确定如何正确处理“ SUM”。)
I started out with the following, but obviously, it's wrong... (it wouldn't "include" Purchases that have an Item with a negative Item.amount...) 我从以下内容开始,但是显然,这是错误的……(它不会“包括”商品的Item.amount为负的购买...)
@users = User.find(:all, @users = User.find(:all,
:include => {:purchases => :item}, :include => {:purchases =>:item},
:select => "SUM(item.amount)", :select =>“ SUM(item.amount)”,
:order => "...", :order =>“ ...”,
:conditions => "...", :conditions =>“ ...”,
:group => "users.id", :group =>“ users.id”,
:having => "SUM(item.amount) > 0" ) :having =>“ SUM(item.amount)> 0”)
Thanks for your help with this! 感谢您的帮助!
Tom 汤姆
Try this: 尝试这个:
User.all(:joins => items, :group => "users.id",
:having => "SUM(items.amount) > 0")
It sounds like this is a good case for some model methods. 对于某些模型方法来说,这似乎是一个很好的例子。
I didn't test this but I think you want to do something similar to the following: 我没有对此进行测试,但我认为您想执行以下操作:
class User < ActiveRecord::Base
has_many :purchases
has_many :items, :through => :purchases
def items_total
#get all the items iterate over them to get the amount,
#compact to get rid of nils
#and reduce with a sum function to total and return
items.all.each{|item| item.amount}.compact.reduce(:+)
end
then 然后
User.items_total
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.