【问题标题】:How to append a string to a text column value in Postgres using Ecto如何使用 Ecto 将字符串附加到 Postgres 中的文本列值
【发布时间】:2023-02-11 11:36:09
【问题描述】:

我有一个带有 dictionaries 表的 postgres 数据库,其中包含一个名为 body 的列。此列有一个 text 数据类型,能够保存无限长度的可变字符串。我正在尝试遍历大型输入流中的行,并将这些行附加到最近插入的行中的此列,其中 kind 列与指定的 arg 匹配。

我试图通过以下方式实现这一目标:

def append_dictionary(kind, line) do
  from(d in Dictionary, where: d.kind == ^kind)
  |> last()
  |> update([d], set: [body: d.body + ^line])
  |> Repo.update_all([])
end

但我收到以下错误:

** (Ecto.QueryError) `update_all` allows only `with_cte`, `where` and `join` expressions.

我只需要将更新应用于 dictionaries 中的最新行,其中 kind 列与提供的 arg 匹配。我怎样才能做到这一点?

这里的另一个重要问题是 Ecto 查询不支持 + 运算符。我应该使用什么来连接更新?

【问题讨论】:

    标签: postgresql elixir ecto


    【解决方案1】:
    def append_dict(kind, line) do
      q = from(dd in Dictionary, where: dd.kind == ^kind, order_by: [desc: dd.id], limit: 1)
    
      from(
        d in Dictionary,
        join: dd in subquery(q),
        on: d.id == dd.id,
        select: d
      )
      |> update([d], set: [body: fragment("? || ?", d.body, ^line)])
      |> Repo.update_all([])
    end
    

    【讨论】:

      猜你喜欢
      • 2017-09-09
      • 2014-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      • 2021-12-20
      • 2018-09-13
      • 2012-07-12
      相关资源
      最近更新 更多