【问题标题】:How to order a query by sum of two columns in Ecto?如何通过 Ecto 中两列的总和对查询进行排序?
【发布时间】:2016-08-30 03:53:49
【问题描述】:

尝试做这样的事情:

(from f in Foo,
 where: f.bar >= ^bar,
 order_by: f.cost1 + f.cost2,
 limit: 1) |> Repo.one

但它不喜欢通过抱怨无效的表达来进行排序。

也试过这个:

(from f in Foo,
 select: %{id: id, total: fragment("cost1 + cost2 as total")},
 order_by: f.total,
 limit: 1) }> Repo.one

这不是说“f.total”列不存在。

任何想法如何使这个查询工作?

【问题讨论】:

    标签: elixir ecto


    【解决方案1】:

    我不确定为什么 Ecto 不支持 order_by: f.cost1 + f.cost2,但您的 fragment 语法不正确。这是正确的语法:

    (from f in Foo,
     where: f.bar >= ^bar,
     order_by: fragment("? + ?", f.cost1, f.cost2),
     limit: 1) |> Repo.one
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      相关资源
      最近更新 更多