使用 sequelize 在 sqlite 数据库中批量更新 table
Bulk update a table in sqlite database using sequelize
我在 sqlite 数据库中有一个 table,其中有一堆记录。我想用某些值更新某些记录的特定列。
例如,如果我有一个名为 'priority' 的列,并且用户更新 'priority' 以获取 ID 为 1,2 和 3 且值为 10,11 和 12 的记录。那么我想更新具有新值的这些记录的各自优先级。
我一直在研究 docs,但还没有找到使用事务进行批量更新的方法。他们说交易 returns 承诺。
在我的特定用例中:
return sequelize.transaction(function (t) {
// chain all your queries here. make sure you return them.
return User.findbyId(1, {transaction: t}).then(function (user) {
return user.updateAttributes({
priority: 10
}, {transaction: t});
});
}).then(function (result) {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback
});
但是,我想像我提到的那样查找和更新一堆行。我必须在 for 循环中做吗?由于事物的异步性质,promise 实现如何处理 for 循环?我想使用事务,因为如果任何更新失败,承诺将不会解决,提交也不会发生。因此,只有在所有更新都成功完成后才会提交。
感谢任何帮助。
你必须在循环时使用 promises:
return sequelize.transaction(function (t) {
return sequelize.Promise.each(thingstoupdate, function (thingtoupdate) {
return thingtoupdate.update(foo, { transaction: t })
});
}).then(function (result) {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback
});
我在 sqlite 数据库中有一个 table,其中有一堆记录。我想用某些值更新某些记录的特定列。
例如,如果我有一个名为 'priority' 的列,并且用户更新 'priority' 以获取 ID 为 1,2 和 3 且值为 10,11 和 12 的记录。那么我想更新具有新值的这些记录的各自优先级。
我一直在研究 docs,但还没有找到使用事务进行批量更新的方法。他们说交易 returns 承诺。
在我的特定用例中:
return sequelize.transaction(function (t) {
// chain all your queries here. make sure you return them.
return User.findbyId(1, {transaction: t}).then(function (user) {
return user.updateAttributes({
priority: 10
}, {transaction: t});
});
}).then(function (result) {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback
});
但是,我想像我提到的那样查找和更新一堆行。我必须在 for 循环中做吗?由于事物的异步性质,promise 实现如何处理 for 循环?我想使用事务,因为如果任何更新失败,承诺将不会解决,提交也不会发生。因此,只有在所有更新都成功完成后才会提交。
感谢任何帮助。
你必须在循环时使用 promises:
return sequelize.transaction(function (t) {
return sequelize.Promise.each(thingstoupdate, function (thingtoupdate) {
return thingtoupdate.update(foo, { transaction: t })
});
}).then(function (result) {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback
});