bookshelf-cascade-delete
This Bookshelf.js plugin provides cascade delete with a simple configuration on your models.
Status
Installation
Install the package via npm
:
$ npm install --save bookshelf-cascade-delete
Usage
Require and register the bookshelf-cascade-delete
plugin:
var bookshelf = require('bookshelf')(knex);
var cascadeDelete = require('bookshelf-cascade-delete');
bookshelf.plugin(cascadeDelete.default);
Define which relations depend on your model when it's destroyed with the dependents
prototype property:
var Post = bookshelf.Model.extend({
tableName: 'Post'
});
var Author = bookshelf.Model.extend({
tableName: 'Author',
posts: function() {
return this.hasMany(Post);
}
}, {
dependents: ['posts']
});
NOTE: This plugin extends the destroy
method of Bookshelf's Model
, so if you are extending or overriding it on your models make sure to call its prototype after your work is done:
var Author = bookshelf.Model.extend({
tableName: 'Author',
posts: function() {
return this.hasMany(Post);
},
destroy: function() {
sendDeleteAccountEmail(this);
bookshelf.Model.prototype.destroy.apply(this, arguments);
}
}, {
dependents: ['posts']
});
Contributing
Feel free to fork this repository and submit pull requests. To run the tests, duplicate the test/mysql.knexfile.js.dist
and test/postgres.knexfile.js.dist
files, update them to your needs and run:
$ npm test
Credits
This plugin's code is heavily inspired on the tkellen contribution for this issue, so cheers to him for making our job really easy!
License
MIT