2016-04-28 30 views
1

我认为字符串concat是<>,但我无法让它在下面的代码中工作。我得到一个错误如何使用Ecto更新字符串

Only literal binaries and strings are allowed, dynamic values need to be explicitly interpolated in queries with ^

我添加^,但它仍然无法正常工作

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>>

回答

3

当你要连接的两个部分之一是从表中的列,你需要的数据库做串联。

Ecto没有功能来做到这一点,所以你必须使用fragment。这应该适用于SQLite和PostgreSQL(我不确定MySQL):

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

我试图在新实例中复制它。 'from(p在Project中,其中:p.id ==^id,update:[set:[jobs:fragment(“?||?”,^ job_id,p.jobs)]])',其中'job_id'是一个整数,'p.jobs'是一个整数数组。我收到错误:'Postgrex预计可以编码/强制输入“_int4”的列表,得到2 .'。我想将2添加到数组 –

+0

您想要将项目2添加到数组中,还是将2添加到数组的每个项目? – Dogbert

+0

'ARRAY [4,5,6]' - >'2 || ARRAY [4,5,6]'c.f. http://www.postgresql.org/docs/9.1/static/functions-array.html –