Need help to DELETE on cascade with sequelize and mySQL

110 Views Asked by At

I know the answer has already been posted several times but no ones has solve my problem.

I just want to delete on cascade my comments when I delete a recipe

Here the relation

db.Recipe.hasMany(db.Comment, { onDelete: 'CASCADE', onUpdate: 'cascade', hooks: true}); db.Comment.belongsTo(db.Recipe, { onDelete: 'CASCADE', onUpdate: 'cascade', hooks: true})

When i delete a recipe

delete: async (id) => {

const isDeleted = await db.Recipe.destroy({  cascade: true, force: true, where: { id }});
  
  return isDeleted === 1;

},

I tried some others things like truncate: true, force: true ... But anytime I delete a recipe, the associated comments just set to NULL.

1

There are 1 best solutions below

1
PAJ On

Try this:

async function deleteRecipe(recipeId) {
  try {
    const recipe = await db.Recipe.findByPk(recipeId);
    await recipe.destroy();
  } catch (error) {
    console.error('Error deleting recipe:', error);
  }
}
        
// Usage
deleteRecipe(your_recipeId);