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 option hooks: true. For instance:
  1. class Projects extends Model {}
  2. Projects.init({
  3. title: DataTypes.STRING
  4. }, { sequelize });
  5. class Tasks extends Model {}
  6. Tasks.init({
  7. title: DataTypes.STRING
  8. }, { sequelize });
  9. Projects.hasMany(Tasks, { onDelete: 'cascade', hooks: true });
  10. 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

  1. 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.