【问题标题】:Elixir / Ecto / Postgres Select multiple columns as oneElixir / Ecto / Postgres 选择多列作为一列
【发布时间】:2017-04-25 16:44:12
【问题描述】:

我只想执行一个包含两列或更多列的简单连接的 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 查询解决这个问题吗?

【问题讨论】:

  • Dogbert 的回答是可行的方法,但我相信对于如此小复杂性的事情,仅在应用程序级别执行它可能是有意义的

标签: postgresql elixir ecto


【解决方案1】:

您不能在 Ecto 的选择表达式中使用 &lt;&gt;。如果你想这样调用concat,你可以使用fragment

select: %{id: c.id, name: fragment("concat(?, ' - ', ?)", c.name, c.street)},

【讨论】:

    【解决方案2】:

    要添加到@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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2021-05-20
      相关资源
      最近更新 更多