[英]Elixir / Ecto / Postgres Select multiple columns as one
I just want do execute an Ecto query with an simple concatination of two or more columns. 我只想用两个或更多列的简单连接来执行Ecto查询。
I think the following elixir pseudo code already shows what I try to do: 我认为以下elixir伪代码已经显示了我尝试做的事情:
customers = Customer.undeleted(
from c in Customer,
select: %{id: c.id, name: c.name <> " – " <> c.street},
order_by: c.name
) |> Repo.all
It drives me crazy cuz in SQL it is easy like this: ...SELECT c.id, concat(c.name, ' - ', c,street) AS name
它让我在SQL中疯狂,因为它很简单: ...SELECT c.id, concat(c.name, ' - ', c,street) AS name
Any ideas how to solve this with ecto querys ? 有任何想法如何用ecto查询来解决这个问题?
You cannot use <>
in a select expression in Ecto. 您不能在Ecto中的选择表达式中使用<>
。 If you want to call concat
like that, you can use fragment
: 如果你想这样调用concat
,你可以使用fragment
:
select: %{id: c.id, name: fragment("concat(?, ' - ', ?)", c.name, c.street)},
To add to @Dogbert answer, you can clean up the code a bit by putting the SQL function fragment in a custom macro as described in the docs : 要添加到@Dogbert答案,您可以通过将SQL函数片段放在自定义宏中来清理代码,如文档中所述:
defmodule CustomSQLFunctions do
defmacro concat(left, mid, right) do
quote do
fragment("concat(?, ?, ?)", unquote(left), unquote(mid), unquote(right))
end
end
end
Then import for use in query 然后导入以供查询使用
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.