Skip to content

Keep getting unique validation error: How to allow duplicate entries in N:M (belongsToMany)? #3220

@maplesap

Description

@maplesap

The unique validation check is preventing me from creating duplicate entries in my join table:

// models/user.js
User.belongsToMany(models.item, { through: models.history, as: "Owners', 
  foreignKey: { 
    name: "itemId",
    allowNull: true,
    unique: false
  }
});

// models/item.js
Item.belongsToMany(models.user, { through: models.history, as: "Owned", 
  foreignKey: {
    unique: false
  }
});

// models/history.js
id: {
  type: DataTypes.INTEGER,
  primaryKey: true,
  autoIncrement: true
},
other: DataTypes.STRING

When a user buys the same item again, resulting in duplicate combinations of itemId and userId in history table, sequelize will throw validation errors:

{ name: 'SequelizeUniqueConstraintError',
  message: 'Validation error',
....
message: "userId" must be unique
type: 'unique violation'
....
message: "itemId" must be unique
type: 'unique violation'

But I have set unique: false on the foreignkeys, and have created a primaryKey for history table, so this validation error confused me. What's the proper way to allow duplicate entries in N:M?

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsFor issues and PRs. Things related to documentation, such as changes in the manuals / API reference.existing workaroundFor issues. There is a known workaround for this issue.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions