I'm using knex in loopback for DB operation with mysql. My task is to update the 2 table by using the transaction. When I enter new entry in one tabe, i want to use id of that entry for 2nd query operation.
But when transaction throw the error it not rolling back the data/ removing the first table entry if second table entry throws error. but in my case transaction always do commit not rollback i put my example code in below:
addTest : (data) => {
return new promise(function(resolve, reject) {
knex.transaction(function(t) {
return knex('foo')
.transacting(t)
.insert({
foo_id: data.foo_id ? data.foo_id : null,
foo_name: data.foo_name ? data.foo_name : null,
date_entered : new Date()
})
.then(function() {
return knex('bar')
.transacting(t)
.insert({
bar_id: data.bar_id ? data.bar_id : null,
bar_name : data.bar_name ? data.bar_name : null
})
})
.then(t.commit)
.catch(function(e) {
t.rollback();
throw e;
})
})
.then(function() {
// it worked
// resolve('sucess');
console.log('success');
})
.catch(function(e) {
// it failed
console.log('error'+e);
});
});
}
please, provide me suitable suggestion. thank you
You can avoid having to call t.commit
or t.rollback
youself. See the docs .
Make your code inside the transaction function something like this
return t.insert({}).into('foo').returning('id') .then( function(idArray) { return t.insert({fooId: idArray[0]}).into('bar') })
That lets knex handle the commiting and rolling back itself based on the result result of that promise. Also, note how I got the inserted fooId
and applied it to the bar
object for insert
ion. That was kind of mentioned in the question.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.