Knex on constraint upsert 冲突

Knex on conflict on constraint upsert

https://knexjs.org/#Builder-onConflict

我没有在文档中找到如何用唯一约束打乱行。

给定以下约束:

ALTER TABLE public.assignments_mappings ADD CONSTRAINT assignments_mappings_task_id_user_id_unique UNIQUE (task_id, user_id)

我正在尝试使用以下代码执行更新插入:

 return await db("assignments_mappings")
      .insert(
        tasksID.map(id => ({ task_id: id, user_id, company_id: 1 }))
      )
      .onConflict('assignments_mappings_task_id_user_id_unique')
      .merge()
      .returning('id')

生成

error: insert into "assignments_mappings" ("company_id", "task_id", "user_id") values (, , ), (, , ), (, , ), (, , ) on conflict ("assignments_mappings_task_id_user_id_unique") do update set "company_id" = excluded."company_id", "task_id" = excluded."task_id", "user_id" = excluded."user_id" returning "id" - column "assignments_mappings_task_id_user_id_unique" does not exist

要成功运行,输出必须是 on conflict on constraint。我该如何解决?

您可以指定构成唯一约束的确切字段名称。

 return await db("assignments_mappings")
      .insert(
        tasksID.map(id => ({ task_id: id, user_id, company_id: 1 }))
      )
      .onConflict(['task_id', 'user_id'])
      .merge()
      .returning('id')