繁体   English   中英

按子模型属性的乘积总和分组

[英]group by sum of products of child model attributes

Document has_many :items

Item belongs_to :document

我需要找到文档,其中items.quantity * items.value_net的乘积之和大于某个值。

我尝试了范围:

scope :items_value_net_gteq, lambda { |value|
  joins(:items)
    .where('SUM(items.quantity * items.price_net) >= ?', value)
}

但这是错误的。 我一定想念一些明显的东西。

您正在寻找having (未测试)的产品:

scope :items_value_net_gteq, ->(value) {
  joins(:items).group('documents.id').
    having('SUM(items.quantity * items.price_net) >= ?', value)
}
scope :items_value_net_gteq, lambda do |value|
  joins(:items).group("items.document_id")
         .having('SUM(items.quantity * items.price_net) >= ?', value)
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM