Sequelize: Update a column value on Model.destroy()

I have a Model written in sequelize with paranoid: true, which means that upon Model.destroy(), the deletedAt column will have datetime value set.

However, I would like a custom column is_archived value set to 1 when Model.destroy() is called without having to make a second Model.update() query after deletion.
I have tried setting instance.is_archived = 1 inside before/afterDestroy hooks, but they do not seem to work.

Any suggestions :)?

Upvotes: 4

Views: 3538

Answers (1)

Dane
Dane

Reputation: 9552

Since there are no answers here, I'm posting this. Sequelize doesn't support updating properties inside beforeDestroy or afterDestroy hooks. The best way to do it is by calling save() or update() inside the hooks:

afterDestroy(instance) {
  instance.is_archived = 1;
  await instance.save({ paranoid: false, hooks: false });
}

It's better to do it inside afterDestroy as the deletion has already taken place. In beforeDestroy there is a chance the instance won't be deleted.

See https://github.com/sequelize/sequelize/issues/9318.

Upvotes: 6

Related Questions