这些表是:
Orders
-----------
user_id
state
Items
-----------
order_id
product_id
total
Products
----------
user_id
Users
---------
name
email
关系如下:
User
has_many :products
Order
has_many :items
belongs_to :users
Product
has_many :items
belongs_to :user
Item
belongs_to :items
我想获得每个拥有该产品的用户的 items.total 的总和
我目前有以下 SQL 语句:
SELECT *, SUM(items.total) as totalprice
FROM "orders"
INNER JOIN "items" ON "items"."order_id" = "orders"."id"
INNER JOIN "products" ON "products"."id" = "items"."product_id"
INNER JOIN "users" ON "users"."id" = "products"."user_id"
WHERE "orders"."state" = 'complete'
GROUP BY users.id
或者
Order.complete.joins(:items => {:product => :user}).select("*, SUM(items.total) as totalprice").group('users.id')
以上不起作用。我觉得这应该很容易。