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
I think you need to define it the other way around.
Contact.belongsTo(models.Users, {
foreignKeyConstraint: true
, onDelete: 'cascade'
})
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.
来源:https://stackoverflow.com/questions/23634139/sequelize-ondelete-not-working