簡體   English   中英

MySQL / Ruby on Rails-如何在:has_many情況下“求和”

[英]MySQL / Ruby on Rails - How to “SUM” in a :has_many case

我有以下表格:

用戶:has_many購買
項目:有許多購買

物料具有“金額”列(可以是+或-),我需要找到所有具有“ SOM.amounts”的正SUM的所有用戶(在每個人進行的所有購買中)。

這個查詢看起來如何? (在這種情況下,我不確定如何正確處理“ SUM”。)

我從以下內容開始,但是顯然,這是錯誤的……(它不會“包括”商品的Item.amount為負的購買...)

@users = User.find(:all,
:include => {:purchases =>:item},
:select =>“ SUM(item.amount)”,
:order =>“ ...”,
:conditions =>“ ...”,
:group =>“ users.id”,
:having =>“ SUM(item.amount)> 0”)

感謝您的幫助!
湯姆

嘗試這個:

User.all(:joins => items, :group => "users.id", 
          :having => "SUM(items.amount) > 0")

對於某些模型方法來說,這似乎是一個很好的例子。

我沒有對此進行測試,但我認為您想執行以下操作:

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

然后

User.items_total

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM