我从3天起就遇到了问题。我想在 Sequelize 中创建多重关系n:m ,但我收到错误消息:" 未处理拒绝SequelizeUniqueConstraint错误:验证错误"
所以我有3张桌子:
以下是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 创建数据库。
非常感谢任何帮助!