Sequelize belongsToMany validation error

走远了吗. 提交于 2019-12-24 07:38:18

问题


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 !

来源:https://stackoverflow.com/questions/42829460/sequelize-belongstomany-validation-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!