简体   繁体   中英

has_many with sum active record

class Product < ActiveRecord::Base

      belongs_to  :category
      has_many  :order_items, dependent: :destroy
    end


class OrderItem < ActiveRecord::Base
  belongs_to :order
  belongs_to :product
end

I need to list all product with their sum of quantity from order_item and sum of their total_price

Product
id    name
1    product_1

OrderItem
product_id order_id quantity total_price
 1            1      10        200
 1            2      10        200

for example expecting output should be
name       quantity   total_price
product_1  20         400

Try this query

select a.name,sum(quantity) as quantity ,sum(total_price) as total_price from 
Product a
join OrderItem b on a.id=b.product_id
Group by a.name
select p.name, sum(o.quantity) as quantity, sum(o.total_price) as total_price
from Product p
  join OrderItem o on p.id = o.product_id
group by p.name

Try this for active records query. just verify your column,table name and associations you can used like:

   OrderItem.joins(:product).select("products.name as name,sum(total_price) as total_price , sum(quantity) as total_quantity").group("order_items.product_id").as_json
p = Product.first
p.order_items.sum(:quantity)

I hope this may also help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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