如何使用Ecto更新字符串

时间:2016-04-28 13:22:57

标签: elixir

我认为字符串concat是<>但我无法在下面的代码中使用它。我收到错误

  

只允许使用文字二进制文件和字符串,需要使用^

在查询中显式插值动态值

我添加了^,但它仍无效

  def delete(conn, %{"id" => id}) do
    card = Repo.get!(Card, id)

    # Look for any cards that have chosen one as master
    # Update name to deleted card + version name
    # remove master_id
    query =
        from(c in Card,
             where: c.master_id == ^id,
             update: [set: [ estimate_name: (^card.estimate_name <> ^c.estimate_name),
                             master_id: 0 ]])
        |> Repo.update_all([])

关于如何解释代码有些奇怪,因为我的字符串字段被读作函数我认为:

<<^card.estimate_name()::binary, ^c.estimate_name()::binary>>

1 个答案:

答案 0 :(得分:3)

由于要连接的两个部分之一是表中的列,因此您需要数据库来进行连接。

Ecto中没有任何功能可以执行此操作,因此您必须使用fragment。这应该适用于SQLite和PostgreSQL(我不确定MySQL):

update: [set: [estimate_name: fragment("? || ?", ^card.estimate_name, c.estimate_name),
               master_id: 0]]