Sequelize onDelete not working
Asked Answered
S

2

6

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

Selfstyled answered 13/5, 2014 at 14:30 Comment(0)
A
8

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

Contact.belongsTo(models.Users, {
    foreignKeyConstraint: true
    , onDelete: 'cascade'
})
Admire answered 13/5, 2014 at 22:22 Comment(4)
Thanks, this worked for me. The documentation is somehow misleading. In the doc, belongsTo does not have the onDelete='CASCADE' option, only hasMany has it. It should really be other way around.Walleyed
Did this way work with onDelete: 'cascade' ? The documentation only shows the cascade option with the hasMany function. i am a bit confused.Thoracotomy
I had to do following as documented (now). User.hasOne(Profile, {onDelete: 'cascade', hooks:true})Plumbism
I had to do as commented here (adding to belongsTo) but also had to remove the use of hasMany in the other model's def. Then I got onDelete cascading.Epochal
H
0

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.

Herculaneum answered 18/7, 2018 at 9:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.