Payalv
Payalv

Reputation: 91

Sequelize - Delete row in junction table when two tables have belongsToMany association

I have two tables in sequelize and they have belongstoMany association with each other. I have a third junction table and I want to delete cascade row from junction table when a row is deleted from two table.

Sequelize version : 3.23.0

I have tried various possibilities to create sequelize table

a) Adding hooks inside association b) Adding foreign key inside association of junction table c) Migration script(https://sequelize.readthedocs.io/en/v3/docs/migrations/) from sequelize (not used before in a project)

Following are my sequelize models

  1. Product models
var product = sequelize.define('product', {
    name: { 
      type: DataTypes.STRING, 
      allowNull: false 
     },
    {
      timestamps: false,
      classMethods: {
        associate: function (models) {

 product.belongsToMany(models.users, {through: 'productUsers', onDelete: 'cascade'});
        }
      }
    });

2.Users model :

  var users = sequelize.define('users', {
    name: {type: DataTypes.STRING, allowNull: false, unique: true},
  },
  {
    classMethods: {
      associate: function(models) {
      users.belongsToMany(models.product, {through:'productUsers', onDelete: 'cascade'});

      }
    }
  });
  1. productUsers junction table
var productUsers = sequelize.define('productUsers', {

}, {
classMethods: {
associate: function (models) {
productUsers.belongsTo(models.product,{onDelete:'cascade'});
productUsers.belongsTo(models.model,{onDelete:'cascade'});
}
}
},
{
timestamps: true
});

Now, I want to delete cascade a row from productUsers table when a product is deleted or a user is deleted. But its not deleting anything from junction table.

Upvotes: 3

Views: 854

Answers (1)

ItaiG
ItaiG

Reputation: 1

According to the sequelize documentation https://sequelize.org/docs/v6/advanced-association-concepts/advanced-many-to-many/

By passing a string to 'through', we are asking Sequelize to automatically generate a model, in your case the 'ProductUsers' junction table. The advantage of an automatic model generation is that it comes with built in functions, which allow to directly link and unlink model instances. The following syntax worked for me: product.addUsers(users) product.removeUsers(users)

Alternatively you can use your own junction model. The association call in this case should be without quotation marks of the model name:

product.belongsToMany(models.User {through: models.ProductUsers})

Then you can add or remove joins by calling the model:

ProductUsers.create({ user_id, product_id })

ProductUsers.destroy({ where: {user_id:something, product_id:something}})

You should consider the proper naming strategies. Check the Sequelize documentation.

Upvotes: 0

Related Questions