Using lifecycle events with associations and transactions
As the default behavior, Sequelize will execute lifecycle events without associating a transaction with any database queries that are invoked within the lifecycle’s scope. However, sometimes our project requires transactions to be used within lifecycle events, such as an accountant’s ledger or creating log entries. Sequelize offers a transaction
parameter when calling certain methods, such as update
, create
, destroy
, and findAll
, that will allow us to use a transaction that was defined outside of the lifecycle’s scope to be used within the lifecycle itself.
Note
When calling beforeDestroy
and afterDestroy
on a model, Sequelize will intentionally skip destroying any associations with that model unless the onDelete
parameter is set to CASCADE
and the hooks
parameter is set to true
. This is due to Sequelize needing to explicitly delete each association row by row, which could cause congestion if we are...