Elixir / Ecto / Postgres Select 多列为一列
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 的 select 表达式中使用 <>
。如果你想这样调用 concat
,你可以使用 fragment
:
select: %{id: c.id, name: fragment("concat(?, ' - ', ?)", c.name, c.street)},
要添加到@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
我只想执行一个包含两个或多个列的简单连接的 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 的 select 表达式中使用 <>
。如果你想这样调用 concat
,你可以使用 fragment
:
select: %{id: c.id, name: fragment("concat(?, ' - ', ?)", c.name, c.street)},
要添加到@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