我是新手,我创建了一个简单的测试文件,该文件使用mysql方言创建了两个模型:Player和Team,并尝试创建一个球员的一个实例,该实例属于一个团队的一个实例。由于某些原因,当我运行以下代码时,出现错误:Cannot delete or update a parent row: a foreign key constraint fails
。
我的代码:
const Player = sequelize.define('player', {
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
}
});
const Team = sequelize.define(`team`, {
teamName: {
type: Sequelize.STRING
},
teamColor: {
type: Sequelize.STRING
},
id: {
type: Sequelize.UUID,
primaryKey: true,
defaultValue: Sequelize.UUIDV1
}
});
Team.hasMany(Player, {
onDelete: 'cascade',
hooks: true
});
Player.belongsTo(Team);
Team.sync({force: true});
// force: true will drop the table if it already exists
Player.sync({force: true}).then(() => {
// Table created
return User.create({
firstName: 'Sagi',
lastName: 'Rika',
Team: {
teamName: 'Worst Team',
teamColor: 'Green'
}
}, {
include: Team
});
});
很抱歉,如果很明显,我只是在文档或堆栈溢出中找不到答案。
谢谢!