如何计算 Elixir 中查询结果的总和?
How can I calculate sum of query results in Elixir?
我有一个 order
table。 table 的其中一列是总价。
Total price
是 order_item
和 item_attribute
的所有价格相加得到的
当用户删除 order_item
时,我想让它删除所有相关的 item_attribute
到 order_item
。所以在计算总价的时候,要扣除order_item
和item_attribute
的价格。
为此,我编写了如下代码
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
删除order_item
和item_attribute
后,选择与order_id
相关的order_item
和item_attribute
的总价之和。然后将其值输入订单数据库。
但是,它会触发 (ArithmeticError) bad argument in arithmetic expression
。这表明 order_total_query = (order_item_total + total_item_attributes_price)
不是算术表达式中的有效参数...
我应该如何计算 order_total_query
正确的算术表达式?
提前致谢。
使用 Repo.aggregate/4 怎么样?
我有一个 order
table。 table 的其中一列是总价。
Total price
是 order_item
和 item_attribute
当用户删除 order_item
时,我想让它删除所有相关的 item_attribute
到 order_item
。所以在计算总价的时候,要扣除order_item
和item_attribute
的价格。
为此,我编写了如下代码
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
删除order_item
和item_attribute
后,选择与order_id
相关的order_item
和item_attribute
的总价之和。然后将其值输入订单数据库。
但是,它会触发 (ArithmeticError) bad argument in arithmetic expression
。这表明 order_total_query = (order_item_total + total_item_attributes_price)
不是算术表达式中的有效参数...
我应该如何计算 order_total_query
正确的算术表达式?
提前致谢。
使用 Repo.aggregate/4 怎么样?