Search code examples
sequelize.js

How to disable unique constraint on composite key in many-to-many relationship?


When 2 models are associated in a many-to-many relation in Sequelize through a junction table, a composite key is created out of the 2 foreign keys from the 2 models. In the sequelize documentation found here: https://sequelize.org/master/manual/advanced-many-to-many.html it says that it's possible to force the table to have a ID privateKey.

A and C are 2 models in a many-to-many relation. The junction table/model is B. Models A and C definition is irrelevant for this example.

//Defining the junction table B with the private key ID
sequelize.define('B', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false
  }
}, { timestamps: false });

A.belongsToMany(Profile, { through: B });
C.belongsToMany(User, { through: B });

Even when adding my ID private key to that table, a unique constraint of those 2 foreign keys still exists. How do I disable that constraint?


Solution

  • ANSWER FOUND

    To anyone browsing the web for the answer, its simple, you have to pass the unique: false option in on the through model.

    A.belongsToMany(Profile, { through: { model: B, unique: false}});
    C.belongsToMany(User, { through:  { model: B, unique: false}});