Skip to content
Advertisement

How to merge and sum up certain values of items that have the same ID value

So i have 2 tables. Orders and OrderItems. Relationship is each Order can have many OrderItems (orderitem is just a product).

OrderItem Table

JavaScript

Orders Table

JavaScript

An order can have the same OrderItem twice or only once. For example like below, 3 items but 2 products:

JavaScript

So above there is 2 entries for Pizza and this is the result i get. However i want it to only show 1 entry for Pizza because its the same item. Below is what i want to see:

JavaScript

So essentially, if the item only exists once, then do nothing to it. If it exists twice, then make the pack_value=1 and the quantity is the sum of the individual quantity*pack_value. So in example above quantity becomes (2*10 + 10*1 = 30).

The controller method is like below, and so here is where I want to do this:

JavaScript

Also the Order and OrderItem models has the method for the relationships. For example, in the Order Model i have:

JavaScript

Thanks, and if you need any extra info i can provide.

Advertisement

Answer

JavaScript

fiddle

Merge another tables to this code using it as subquery, or add them into FROM clause (adjusting its output list and grouping expression) if needed.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement