我正在使用 knexjs 从表中删除一行。该表引用了另一个表中的行,因此我需要先删除这些子行才能删除父行。我想使用事务,以便在父删除失败时可以回滚子删除。
这是我的代码,但它似乎卡在第二个查询上:
return Bookshelf.knex.transaction((t : any) => {
return Bookshelf.knex('user_patient_groups')
.transacting(t)
.del()
.where('patient_group_id', groupID)
.then(() => {
return Bookshelf.knex('patient_groups')
.del()
.where('patient_group_id', groupID)
.then(t.commit)
.catch(t.rollback);
});
});
有人可以看看我在这里做错了什么吗? knexjs 文档不是很广泛。
最佳答案
您应该省略调用
.then(t.commit)
.catch(t.rollback)
如果交易回调中返回了promise,knex
将为您管理您的交易。因此,使用您的 .catch
您可以抑制通过 promise 链传递的错误,并且交易会看到已履行的 promise 。
否则,不要从事务中返回 promise (删除返回
)并保留提交
和回滚
。
关于node.js - knexjs 使用事务从父/子表中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47783928/