How to order a query for the sum of two columns in Ecto?

Trying to do something like this:

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

But he does not like the order, complaining of an unacceptable expression.

Also tried the following:

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

This does not say that the column "f.total" does not exist.

Any ideas how to make this request work?

+4
source share
1 answer

I'm not sure why Ecto does not support order_by: f.cost1 + f.cost2, but your syntax is fragmentincorrect. Here is the correct syntax:

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

Source: https://habr.com/ru/post/1652913/


All Articles