Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transaction for collection

How can I do using transacting t, I want to make sure the row is successful remove before saving the record:

var Roles = bookshelf.Collection.extend({
     model: Role
);

Role.where('name', '=', 'Staff').destroy();

var roles = Roles.forge([{name: 'Staff'}, {name: 'Guest'}]);

Promise.all(roles.invoke('save')).then(function(role) {
    resolve(role);
}).catch(function (err) {
    reject({"status":"error", "data": err});
});
like image 724
Alvin Avatar asked Mar 12 '26 20:03

Alvin


1 Answers

You may just use Bookshelf's transaction() method.

But first your save() MUST be in the context of the destroy() promise, so ensuring proper sequence, otherwise you risk having your saved data being also deleted by the destroy.

So it may look like:

var Roles = bookshelf.Collection.extend({
  model: Role
});

bookshelf.transaction(function(t) {
  return Role
    .where('name', '=', 'Staff')
    .destroy({transacting: t})
    .then(function() {
      var roles = Roles.forge([{name: 'Staff'}, {name: 'Guest'}]);
      return roles
        .invokeThen('save', null, {transacting: t});
    });
});
like image 117
flaviodesousa Avatar answered Mar 15 '26 13:03

flaviodesousa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!