【问题标题】:Sum table column if an associated tables field meets condition如果关联的表字段满足条件,则汇总表列
【发布时间】:2014-02-25 02:00:51
【问题描述】:

我正在尝试学习与 Rails 4 的数据库关联。

在我的应用程序中,我有两个模型,销售和产品。

class Sale < ActiveRecord::Base

    belongs_to :customer
    belongs_to :product

end

class Product < ActiveRecord::Base

    self.primary_key = :product_id

    has_many :sales

end

我已经建立了与 has_many 和 belongs_to 的关联,并且在 Rails 控制台中我可以成功地做到:

@s = Sale.find_by_product_id("10RB1236").product.product_group_id

  Sale Load (1.5ms)  SELECT "sales".* FROM "sales" WHERE "sales"."product_id" =     '10RB1236' LIMIT 1
  Product Load (0.8ms)  SELECT "products".* FROM "products" WHERE "products"."product_id" = $1 ORDER BY "products"."product_id" ASC LIMIT 1  [["product_id", "10RB1236"]]
 => "30" 

这成功返回 product_group_id 为“30”。我的学习协会的里程碑:) 对此感到高兴。

但是现在我希望能够返回与 product_id 关联的 product_group_id 等于 30 的 net_amount 的总和。这样我就可以得到数据库中满足此条件的所有行的总 net_amount。

我试过了:

@c = Sale.sum(:net_amount, :conditions => {:product_id.product_group_id => "30"})
@c = Sale.sum(:net_amount, :conditions => {:product_id.product.product_group_id => "30"})

只是想获得更多关于如何做到这一点的想法或解决方案?如果我在纯 SQL 中执行此操作,我想我会在某处发生内部连接。

任何想法都将不胜感激。

【问题讨论】:

标签: ruby ruby-on-rails-4 associations has-many belongs-to


【解决方案1】:
Sale.includes(:product).where("products.product_group_id = ?", "30").sum(:net_amount)

【讨论】:

  • 嗨,bjhaid,感谢您的建议。它在哪里指定 product_group_id 等于 30?还要澄清一下,在 sale 表中可能有许多 product_ids 的 product_group_id 等于“30”,而不仅仅是“10RB1236”。
  • 好的,谢谢你澄清我可能不需要加入,我会继续挖掘。我怀疑我在某个地方对我的协会感到厌烦,或者我需要回到教室去讨论协会。
  • 如果情况变得更糟,我可以更改我的销售表以包含 product_group_id 和 product_id。我很确定这个答案是显而易见的,但作为一个菜鸟,我会同时查看一百万个地方。
  • @JayKilleen 我想我错过了你的问题,我已经更新了我的答案
  • 试一试,这是控制台输出。 Sale.joins(:product).where(:product_group_id => "30").sum(:net_amount) SELECT SUM("sales"."net_amount") AS sum_id FROM "sales" INNER JOIN "products" ON "products" ."product_id" = "sales"."product_id" WHERE "sales"."product_group_id" = '30' PG::Error: ERROR: column sales.product_group_id does not exist LINE 1: ...oducts"."product_id" = "销售"."product_id" WHERE "销售"."p...
猜你喜欢
  • 1970-01-01
  • 2017-05-13
  • 1970-01-01
  • 2022-10-07
  • 1970-01-01
  • 2020-06-27
  • 2016-06-13
  • 1970-01-01
  • 2020-01-22
相关资源
最近更新 更多