我只想用两个或多个列的简单连接来执行Ecto查询。
我认为以下elixir伪代码已经显示了我尝试做的事情:
customers = Customer.undeleted(
from c in Customer,
select: %{id: c.id, name: c.name <> " – " <> c.street},
order_by: c.name
) |> Repo.all
它让我在SQL中疯狂,因为它很简单:...SELECT c.id, concat(c.name, ' - ', c,street) AS name
有关如何使用ecto querys解决此问题的任何想法?
答案 0 :(得分:6)
您不能在Ecto中的选择表达式中使用<>
。如果您想这样致电concat
,可以使用fragment
:
select: %{id: c.id, name: fragment("concat(?, ' - ', ?)", c.name, c.street)},
答案 1 :(得分:0)
要添加到@Dogbert答案,您可以通过将SQL函数片段放在自定义宏中来清理代码,如docs中所述:
defmodule CustomSQLFunctions do
defmacro concat(left, mid, right) do
quote do
fragment("concat(?, ?, ?)", unquote(left), unquote(mid), unquote(right))
end
end
end
然后导入以用于查询
import CustomSQLFunctions
customers = Customer.undeleted(
from c in Customer,
select: %{id: c.id, name: concat(c.name, ' - ', c.street)},
order_by: c.name
) |> Repo.all