I have an order table. One of columns of this table is total price.
Total price is calculated by adding up all prices of order_item and item_attribute
When a user deletes an order_item, I want to make it delete all of related item_attribute to order_item. So when it calculates total price, it should deduct price of order_item and item_attribute.
So to do that I made code like below
order_item_total = Repo.one!(from p in Pos8.OrderItem, where: p.order_id == ^order_id, select: sum(p.item_total))
total_item_attributes_price = Repo.one!(from p in Pos8.ItemAttribute, where: p.order_id == ^order_id, select: sum(p.price))
order_total_query = (order_item_total + total_item_attributes_price)
Pos8.Order.changeset(order, %{total: order_total_query})
|> Repo.insert_or_update
After delete order_item and item_attribute, it selects sum of total price of order_item and item_attribute, which are related to order_id. And then input its value to Order database.
However, it triggers (ArithmeticError) bad argument in arithmetic expression. Which shows that order_total_query = (order_item_total + total_item_attributes_price) is not valid argument in arithmetic expression...
How should I calculate order_total_queryin correct arithmetic expression?
Thanks in advance.
How about using Repo.aggregate/4 ?