Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sails.js + waterline One-To-Many model association, what should happen when deleting the Many?

I have a one to many relation between Teacher(One) and Children(Many).

If I do:

Teacher.destroy(teacherId).exec(function(err){});

The children are not automatically removed.

Is it a bug or should I delete them manually? If that's not a bug, what is the explanation for not deleting children?

like image 735
user2867106 Avatar asked May 05 '14 23:05

user2867106


1 Answers

Waterline currently doesn't support cascading deletes. It may be a configuration option in future versions, but it will probably never be the default. In most production-ready apps you probably should be doing soft-deletes anyway. In either case, you can get what you want by using the afterDestroy lifecycle callback.

In api/models/Teacher.js, something like:

module.exports = {
    attributes: {
       // attributes here
    },
    afterDestroy: function(destroyedRecords, cb) {
        // Destroy any child whose teacher has an ID of one of the 
        // deleted teacher models
        Child.destroy({teacher: _.pluck(destroyedRecords, 'id')}).exec(cb);
    }
}

You could do something similar with soft-deletes using the afterUpdate method.

like image 120
sgress454 Avatar answered Oct 13 '22 13:10

sgress454