[英]Elixir / Ecto / Postgres Select multiple columns as one
我只想用两个或更多列的简单连接来执行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查询来解决这个问题?
您不能在Ecto中的选择表达式中使用<>
。 如果你想这样调用concat
,你可以使用fragment
:
select: %{id: c.id, name: fragment("concat(?, ' - ', ?)", c.name, c.street)},
要添加到@Dogbert答案,您可以通过将SQL函数片段放在自定义宏中来清理代码,如文档中所述:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.