我是新开发人员,正在尝试通过一些小测试项目自学 Sequelize 和 mysql。我现在拥有的是一个小型 Angular 色扮演游戏团队实力分析器。我有一个单位的 SQL 表,它有模式(id、名称、elementOne、elementTwo)——整数、字符串、字符串、字符串。
目前,elementOne 和 ElementTwo 表都是相同的 18 个字符串值,因为我无法弄清楚如何使用指向同一个表的外键引用(例如,只是“元素”)来设置 Sequelize 查询。
添加到 Unit 表在本地服务器上工作正常,但仅在尝试添加 third 单元时在 Heroku 上中断并出现以下错误:
Error was: { SequelizeForeignKeyConstraintError: Cannot add or update a child
row: a foreign key constraint fails (`heroku_f4daeab1e260595`.`units`,
CONSTRAINT `units_ibfk_1` FOREIGN KEY (`id`) REFERENCES `elementtwos` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE)
这里是所有的表和关系声明。
const Unit = sequelize.define('unit', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
unique: true,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false,
unique: false
},
image: {
type: Sequelize.STRING,
allowNull: true,
unique: false
},
elementOne: {
type: Sequelize.INTEGER,
allowNull: true,
references: {
model: Element,
key: 'id'
}
},
elementTwo: {
type: Sequelize.INTEGER,
allowNull: true,
defaultValue: 10001,
references: {
model: ElementTwo,
key: 'id'
}
}
});
const Element = sequelize.define('element', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
unique: true,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false,
unique: false
}
});
const ElementTwo = sequelize.define('elementtwo', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
unique: true,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false,
unique: false
}
});
这些都加载完后,我设置如下:
Unit.belongsTo(Element, {foreignKey: 'elementOne'});
Unit.belongsTo(ElementTwo, {foreignKey: 'elementTwo'});
ElementTwo.hasMany(Unit, {foreignKey: 'id'});
Element.hasMany(Unit, {foreignKey: 'id'});
这是 Sequelize 正在执行的查询(在 Unit.create({...}) 中):
INSERT INTO `units`
(`id`,`name`,`image`,`elementOne`,`elementTwo`,`createdAt`,`updatedAt`) VALUES
(DEFAULT,'raichu','http://longimgurl.png',13,10001,'2017-06-14
12:57:54','2017-06-14 12:57:54');
如果有人可以提供任何建议,我们将不胜感激。
最佳答案
这是 mysql 错误,因为你在你的表上定义了外键约束,并试图在目标表中不存在的 fk 字段中插入不可用的值,
检查 element
和 elementTwo
表并确保这些值可用
关于javascript - Sequelize Heroku 上的外键错误但不是本地测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44546032/