Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)?

like image 471
Khawaja Muhammad Ahsen Avatar asked Sep 13 '25 16:09

Khawaja Muhammad Ahsen


1 Answers

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.

like image 154
Dane Avatar answered Sep 16 '25 09:09

Dane