Reputation: 4847
I have a table in a sqlite database with a bunch of records. I want to update a specific column for some records with some values.
For instance if I have a column named 'priority' and the user updates 'priority' for records with IDs 1,2 and 3 with values 10,11, and 12. Then I want to update the respective priorities for these records with the new values.
I have been going through the docs but haven't yet found a way to do a bulk update using a transaction. They say that a transaction returns a promise.
In my particular use-case:
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
});
However, I want to do that find and update for a bunch of rows like I mentioned. Do I have to do in a for loop? How does the promise implementation take care of the for loop because of the async nature of things? I would want to use transactions because if any of the updates fail, the promise won't resolve and the commit won't take place. So, the commit happens only when all the updates get successfully done.
Any help is appreciated.
Upvotes: 2
Views: 1712
Reputation: 28788
You have to use promises when loop:
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
});
Upvotes: 3