我想使用Knex.js执行批量更新
例如:
'UPDATE foo SET [theValues] WHERE idFoo = 1'
'UPDATE foo SET [theValues] WHERE idFoo = 2'
Run Code Online (Sandbox Code Playgroud)
值:
{ name: "FooName1", checked: true } // to `idFoo = 1`
{ name: "FooName2", checked: false } // to `idFoo = 2`
Run Code Online (Sandbox Code Playgroud)
我之前使用的是node-mysql,它允许多个语句.使用它时我只是构建了一个多语句查询字符串,只需在一次运行中通过线路发送.
我不确定如何用Knex实现同样的目标.我可以batchInsert看作我可以使用的API方法,但就任何batchUpdate问题而言都没有.
我可以进行异步迭代并分别更新每一行.这是不好的原因,这意味着从服务器到数据库将会有很多往返
我可以使用raw()Knex 的东西,可能做类似于我对node-mysql的操作.然而,这破坏了作为DB抽象层的整个knex目的(它引入了强大的DB耦合)
所以我想用"knex-y"来做这件事.
欢迎任何想法.
如何优化此代码?我不想在哪里打电话2次...有没有比这更好的查询了?
return self.db.clientDevices.where(device).then(function (rows) {
if (rows.length != 1) {
device.key = value;
self.db.clientDevices.insert(device).then();
} else {
self.db.clientDevices.where(device).update(device).then();
}
});
Run Code Online (Sandbox Code Playgroud)