如何在Ecto中按两列的总和来订购查询?

DCa*_*uch 4 elixir ecto

试着这样做:

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

但它不喜欢这个命令,抱怨表达无效.

还试过这个:

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

这个没有说列"f.total"不存在.

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

Dog*_*ert 6

我不确定为什么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
Run Code Online (Sandbox Code Playgroud)