Associations
For the most part hooks will work the same for instances when being associated except a few things
- When using add/set functions the beforeUpdate/afterUpdate hooks will run.
- The only way to call beforeDestroy/afterDestroy hooks are on associations with
onDelete: 'cascade'
and the optionhooks: true
. For instance:
class Projects extends Model {}
Projects.init({
title: DataTypes.STRING
}, { sequelize });
class Tasks extends Model {}
Tasks.init({
title: DataTypes.STRING
}, { sequelize });
Projects.hasMany(Tasks, { onDelete: 'cascade', hooks: true });
Tasks.belongsTo(Projects);
This code will run beforeDestroy/afterDestroy on the Tasks table. Sequelize, by default, will try to optimize your queries as much as possible. When calling cascade on delete, Sequelize will simply execute a
DELETE FROM `table` WHERE associatedIdentifier = associatedIdentifier.primaryKey
However, adding hooks: true
explicitly tells Sequelize that optimization is not of your concern and will perform a SELECT
on the associated objects and destroy each instance one by one in order to be able to call the hooks with the right parameters.
If your association is of type n:m
, you may be interested in firing hooks on the through model when using the remove
call. Internally, sequelize is using Model.destroy
resulting in calling the bulkDestroy
instead of the before/afterDestroy
hooks on each through instance.
This can be simply solved by passing {individualHooks: true}
to the remove
call, resulting on each hook to be called on each removed through instance object.