Rails 3 ActiveRecord查询:查找该用户已订购的该产品的数量
我有一个 belongs_to :user
的 order
模型、一个 product
模型、一个连接模型 order_product
class OrderProduct < ActiveRecord::Base
belongs_to :order
belongs_to :product
end
: >order_product 模型有一个 quantity
列。
如何查找用户 u
订购了多少产品 p
?我想找到一个使用 Rails 3 的活动记录查询语法并尽可能在数据库级别进行的解决方案。我将不胜感激任何帮助。
I have an order
model that belongs_to :user
, a product
model, a join model order_product
:
class OrderProduct < ActiveRecord::Base
belongs_to :order
belongs_to :product
end
The order_product
model has a quantity
column.
How can I find how many of a product p
have been ordered by a user u
? I would like to find a solution that uses rails 3's active record query syntax and takes place at the database level as much as possible please. I'd appreciate any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该可以解决问题:
这是一个单一的 SQL 查询,适合显示一种产品。如果您要显示多个产品,那么您将按产品 ID 进行分组,从而为您提供一个值的哈希值,您可以从中进行查找。
That should do the trick:
That's a single SQL query, good for displaying one product. If you're displaying multiple products, then you would group by product ID, thereby giving you a Hash of values, from which you do your lookups.
如果你想使用 Rails 3 查询链
p.order_product.includes("order").where(:orders => {:user_id => 'user_id'}).sum(:quantity) ,
它可能类似于下面的内容尝试看看是否有效,也许我错过了一些东西
It can be something like below if you want to use Rails 3 query chain
p.order_product.includes("order").where(:orders => {:user_id => 'user_id'}).sum(:quantity)
Try to see if it works, maybe i miss out something