我想使用执行批量更新Knex.js http://knexjs.org/
例如:
'UPDATE foo SET [theValues] WHERE idFoo = 1'
'UPDATE foo SET [theValues] WHERE idFoo = 2'
具有值:
{ name: "FooName1", checked: true } // to `idFoo = 1`
{ name: "FooName2", checked: false } // to `idFoo = 2`
我正在使用节点mysql https://github.com/mysqljs/mysql#multiple-statement-queries以前,它允许多个语句。在使用它时,我只是构建了一个多语句查询字符串,然后通过一次运行将其发送。
我不知道如何用 Knex 实现同样的目标。我可以看到batchInsert
作为一个API方法我可以使用,但没有什么batchUpdate
被关注到。
Note:
所以我想使用“knex-y”来做到这一点。
欢迎任何想法。
我需要在事务内执行批量更新(我不想进行部分更新,以防出现问题)。
我已经用下一个方法解决了:
// I wrap knex as 'connection'
return connection.transaction(trx => {
const queries = [];
users.forEach(user => {
const query = connection('users')
.where('id', user.id)
.update({
lastActivity: user.lastActivity,
points: user.points,
})
.transacting(trx); // This makes every update be in the same transaction
queries.push(query);
});
Promise.all(queries) // Once every query is written
.then(trx.commit) // We try to execute all of them
.catch(trx.rollback); // And rollback in case any of them goes wrong
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)