How to delete all FK records by deleting their "owner" with Sequelize?

Asked

Viewed 90 times

2

I’m making a database and it has some properties and it has users.

A user can have several properties, so in the properties table I inserted the column user_id, to reference the user.

But when I create the properties table by sequelize-cli. FK looks like this:

user_id: {
  type:Sequelize.INTEGER,
  references: { model:'users', key:'id'},
  onUpdate:'NO ACTION',
  onDelete:'NO ACTION',
  allowNull:false
}

The onUpdate, would be when deleting a property, doing nothing on users and the same thing to onDelete. But here comes my question, I wanted that when I deleted the user, also delete all properties that it has.

How do I do that?

NOTE: Admit properties as real estate

1 answer

1

In that case (one for many - N:M) would be assign to the onDelete the value CASCADE, where now, when the user is removed, all properties (user related) will also be removed.

user_id: {
  type:Sequelize.INTEGER,
  references: { model:'users', key:'id'},
  onUpdate:'NO ACTION',
  onDelete:'CASCADE',
  allowNull:false
}

Remembering that in the documentation, your onUpdate, by default, also has value CASCADE,which indicates that the referential action will be executed when a record is modified in the parent table (user table), so I suggest you change the onUpdate for CASCADE also, unless you don’t find it necessary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.