我有三个模型:Sale
,Product
和Client
。一笔销售既属于产品,也属于客户,两者都有很多销售。客户还通过销售获得了许多产品(基本上是曾经卖给该客户的产品)。 client.products
的查询是
SELECT "products".* FROM "products" INNER JOIN "sales" ON "products"."id" = "sales"."product_id" WHERE "sales"."client_id" = $1
到目前为止,太好了。现在,我想急于增加属于某个客户(client.products.includes(:sales)
)的产品的销售量,这样可以正确获取该客户的每种产品的所有销售量,如下所示:
SELECT "products".* FROM "products" INNER JOIN "sales" ON "products"."id" = "sales"."product_id" WHERE "sales"."client_id" = $1;
SELECT "sales".* FROM "sales" WHERE "sales"."product_id" IN (...)
问题是我只想获取属于该客户的销售。查询应如下所示:
SELECT "products".* FROM "products" INNER JOIN "sales" ON "products"."id" = "sales"."product_id" WHERE "sales"."client_id" = $1;
SELECT "sales".* FROM "sales" WHERE "sales"."client_id" = $1 AND "sales"."product_id" IN (...)
我尝试做
client.products.includes(:sales).where(sales: { client: client } })
和
client.products.includes(:sales).where(products: { sales: { client: client } })
但不幸的是,它只会更改第一个查询,如下所示:
WHERE "sales"."client_id" = $1 AND "sales"."client_id" = $2
$ 1和$ 2是相同的值。
使用includes
甚至可以做到吗?如果是这样,我该怎么办?
答案 0 :(得分:1)
sales = client.sales.includes(:product)
这将为您返回所有销售并渴望为销售/客户加载产品。
要获得产品,您可以循环销售
sales.each do |sale|
sale.product
end
编辑
您可以按产品分组销售
products_with_sales = sales.group_by(&:product)
这将返回哈希数组
key = product
value = [sales]
然后您可以执行计算
products_with_sales.each do |product, sales|
# sales.map { ... }
# sales.sum(&:method)
end