首页 > 解决方案 > 使用 knexjs 检测并发出 onConflict 信号

问题描述

此处的此文档解释了使用onConflict()andignore()将简单地安静地放弃该操作。如果我试图将新行插入到表中,如下所示:

const addItem = (item) => {
  return database(dbTable).insert(item)
                .onConflict('name')
                .ignore()
                .then(() => {
                }).catch((err) => {
                    console.log(err)
                })
}

如果不是ignoring,我如何(或在哪里)向调用该函数的外部调用返回某种信号addItem?例如,0如果没有冲突(并且添加项目)则返回;1如果有冲突返回(并且承诺悄悄地解决而不做任何事情)?谢谢

标签: javascriptnode.jsknex.js

解决方案


可能是依赖于数据库的功能,但是例如,如果您使用 postgres 插入并且它不返回任何行,则意味着存在此问题中提到的冲突:

如何在 PostgreSQL 中使用 RETURNING 和 ON CONFLICT?

似乎也.returning('*')可以与.onConflict(...).ignore()

https://runkit.com/embed/6p825ex0xt4b

knex('table').insert({a: 1, b:2}).onConflict('id').ignore().returning('*').toSQL().sql;

// knex 0.21.15 returns: 
// insert into "table" ("a", "b") values (?, ?) 
//    on conflict ("id") do nothing returning *

推荐阅读