I have a scenario involving two tables (one-to-many), where a user can delete a record or array of records from the first table (name: document, relationship: one) and then the record(s) associated to that table from my second table (name: file, relationship: many) will be removed. The onDelete cascading on the "file" table is working as it should, but my hook is never firing.
- Do I need to call the hook somewhere within my
.destroysequelize method? - Because my relationship one-to-many where a user can have multiple
files or a single file for one document, do I need to add hooks for
both
beforeDestroyandbeforeBulkDestroy?
Here is the association between the two tables:
Document
var Document = sequelize.define('document', {
...
},
{
underscored: true,
freezeTableName: true,
classMethods: {
associate: function(db) {
Document.hasMany(db.File, { foreignKey: 'document_id'}),
}
}
});
return Document;
File
var File = sequelize.define('file', {
...
},{
underscored: true,
freezeTableName: true,
hooks: {
beforeDestroy: function(whereClause, fn){
//options.individualHooks = true;
console.log('whereClause Start');
console.log(whereClause);
console.log('fn start');
console.log(fn);
},
beforeBulkDestroy: function(whereClause, fn) {
//options.individualHooks = true;
console.log('whereClause Start');
console.log(whereClause);
console.log('fn start');
console.log(fn);
}
},
classMethods: {
associate: function(db) {
File.belongsTo(db.Document, { onDelete: 'CASCADE', hooks: true});
}
}
});
return File;
Only Sequelize trigger scenario:
models.Document.destroy({
where: {
userId: req.user.userId,
documentId: documentId //Replace with array in certain instances
}
});