1

I'm facing a problem since 3 days. I would like to create a multiple relation n:m in Sequelize but I'm getting an error message : "Unhandled rejection SequelizeUniqueConstraintError: Validation error".

So I have 3 tables :

  • Serie.
  • Episode.
  • Season (in this table I would like to add relation to Serie and Episode).

Here is the definition of Serie :

var Serie = sequelize.define('Serie', {
      idSerie: {
          type: DataTypes.INTEGER,
          primaryKey: true,
          autoIncrement: true
      },
      name: DataTypes.STRING
    }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
      }
    }
  });

Episode :

var Episode = sequelize.define('Episode', {
      idEpisode: {
          type: DataTypes.INTEGER,
          primaryKey: true,
          autoIncrement: true
      },
      description: DataTypes.TEXT
    }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
      }
    }
  });

And Season :

var Season = sequelize.define('Season', {
        idSeason: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        numero: DataTypes.INTEGER,
        idEpisode: DataTypes.INTEGER,
        idSerie: DataTypes.INTEGER
    }, {
    classMethods: {
        associate: function(models) {
            // associations can be defined here

            models.Episode.belongsToMany(models.Serie, { through: models.Season, foreignKey: 'idEpisode', otherKey:'idSerie' });
            models.Serie.belongsToMany(models.Episode, { through: models.Season, foreignKey: 'idSerie', otherKey:'idEpisode' });
      }
    }
  });

To add a new relation I used this :

// serieFound was fetched using findOne and newEpisode was created
serieFound.addEpisode(newEpisode);

PS: I'm using sequelize-cli to create DB.

Any help would be greatly appreciated !

iStornZ
  • 603
  • 1
  • 8
  • 19
  • Do you predict a situation where the same episode is assign to the same serie twice? Maybe that's the case – piotrbienias Mar 16 '17 at 09:16
  • Sorry but I don't understand what you mean by assigning twice ? Same object ? – iStornZ Mar 16 '17 at 09:41
  • For example if you assign `Episode` with `idEpisode: 1` to the same serie twice (like `serieFound.addEpisode(1)` called twice). – piotrbienias Mar 16 '17 at 09:46
  • Oh ok, nop addEpisode() is called just one time :/ – iStornZ Mar 16 '17 at 19:50
  • On the log, here is the last SQL query : INSERT INTO `Seasons` (`idSeason`,`idEpisode`,`idSerie`,`createdAt`,`updatedAt`) VALUES (NULL,1,1,'2017-03-16 19:49:21.243 +00:00','2017-03-16 19:49:21.243 +00:00'); – iStornZ Mar 16 '17 at 19:50

0 Answers0