【问题标题】:How can I calculate sum of query results in Elixir?如何计算 Elixir 中查询结果的总和?
【发布时间】:2017-01-04 08:23:58
【问题描述】:

我有一个order 表。该表的一列是总价。

Total price 的计算方法是将order_itemitem_attribute 的所有价格相加

当用户删除order_item 时,我想让它删除所有相关的item_attributeorder_item。所以在计算总价时,要减去order_itemitem_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_itemitem_attribute后,选择与order_id相关的order_itemitem_attribute的总价之和。然后将其值输入订单数据库。

但是,它会触发(ArithmeticError) bad argument in arithmetic expression。这表明order_total_query = (order_item_total + total_item_attributes_price) 不是算术表达式中的有效参数...

我应该如何在正确的算术表达式中计算order_total_query

提前致谢。

【问题讨论】:

  • 打印order_item_totaltotal_item_attributes_price的值会帮你

标签: elixir phoenix-framework arithmetic-expressions


【解决方案1】:

使用Repo.aggregate/4 怎么样?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    相关资源
    最近更新 更多