Sequelize onDelete not working

2019-01-25 23:14发布

问题:

I have associations between two models defined as below:

For Contact Model (in a separate file)

classMethods: {
      associate: function (models){
         Contact.belongsTo(models.User)
      }
}

For User(in a separate file)

classMethods: {
     associate: function (models){
        User.hasMany(models.Contact, {onDelete: 'CASCADE'})
     }
}

The problem is when deleting the user the contact related to the user is not deleting any advice on what am I doing wrong would be helpful?

Thanks in advance

回答1:

I think you need to define it the other way around.

Contact.belongsTo(models.Users, {
    foreignKeyConstraint: true
    , onDelete: 'cascade'
})


回答2:

Update association to User.hasMany(models.Contact, { onDelete: 'cascade', hooks: true }) to allow the hooks between associations to fire in order to enable the onDelete cascade. Adapted from the sequelize docs:

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.