我创建了以下两个模型...
const Account = sequelize.define("account",
{
id_account: {
type: Sequelize.INTEGER.UNSIGNED,
primaryKey: true,
autoIncrement: true
},
name: {...},
surname: {...},
username: {...},
password: {...}
},
{
name: {
singular: "Account",
plural: "Accounts"
},
freezeTableName: true,
hooks: {
beforeSave: ((account, options) => {
return bcrypt.hash(account.password, 10)
.then(hash => {account.password = hash;})
.catch(err => {throw new Error();});
})
}
});
const Genre = sequelize.define("genre",
{
genre_name: {
type: Sequelize.STRING(40),
primaryKey: true
},
url_img: {
type: Sequelize.STRING(40),
allowNull: false
}
},
{
name: {
singular: "Genre",
plural: "Genres"
},
freezeTableName: true
});
...以及以下关联
Account.Genres = Account.belongsToMany(Genre, {
through: "AccountGenre",
foreignKey: "ref_account"
});
Genre.Accounts = Genere.belongsToMany(Account, {
through: "AccountGenre",
foreignKey: "ref_genre"
});
我创建了以下类型:摇滚,金属,流行,铁杆。 现在,我想创建一个帐户并将其与3种类型相关联。 以下代码创建了Account,但未与AccountGenre表中的现有流派建立关联:
const genresArray = ["Rock", "Metal", "Pop"];
const account = {...} // I have an object with account properties
Account.create({
name: account.name,
surname: account.cognome,
username: account.nome_utente,
password: account.password,
genres: genresArray
}, {
include: [Genre]
});
此代码有什么问题?
答案 0 :(得分:0)
这里的问题是您给了 复数名称“流派”的关联。您需要在include语句中添加相同的内容。
包括:[类型]