Question

Let's say I have got 2 models.

User and Clubs.

To simplify my problem let's say that User got only Id and Clubs got the ClubId and UserId so one club can have many different users.

Here is my problem :

When I delete for example User with Id 3, I want also to delete all Users from Clubs with this Id 3. How to make it happen?

Was it helpful?

Solution

Sails doesn't support cascading deletes yet, but you can handle this yourself:

User.destroy({id:3}).exec(function(err, users) {
   if (err) {return res.serverError();}
   var userIds = users.map(function(user){return user.id;});
   Club.destroy({user_id: userIds}).exec(function(err, clubs) {
      // do something
   });
});

destroy returns an array of all the objects that were destroyed. In your case, since you're searching by ID, only one would (hopefully) be returned, but if you were using criteria that could destroy several users at once you could still use the above code to wipe out all the related clubs.

OTHER TIPS

You can get afterDestroy event after deleting any model. Simple demo as below

In comtroller :

 Company.destroy({id: 12346798})
    .exec(function(e,r){

          return res.json(r);
    });

In Company.js model :

afterDestroy: function(destroyedCompany, cb) {

    var ids = _.pluck(destroyedCompany, 'id');

    if(ids && ids.length){

         Department.destroy({company_id: ids})
        .exec(function(e,r){
            CompanyArticle.destroy({company_id: ids}).exec(cb);
        });

    }
    else{
        cb();
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top