自3天以来,我一直面临一个问题。我想在Sequelize中创建一个多重关系 n:m ,但我收到一条错误消息:“未处理的拒绝 SequelizeUniqueConstraintError:验证错误”。
所以我有 3 张桌子:
- 意甲。
- 插曲。
- 季节(在此表中,我想添加与Serie和Episode的关系)。
这是 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
}
}
});
情节:
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
}
}
});
和季节:
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' });
}
}
});
要添加一个新关系,我使用了这个:
// serieFound was fetched using findOne and newEpisode was created
serieFound.addEpisode(newEpisode);
PS:我正在使用sequelize-cli创建数据库。
任何帮助将不胜感激 !