Mysql 无法添加或更新子行:外键约束失败约束`PageChild\u Page\u Id\u fk`外键(`PageId`)引用`Page`(`Id`)
我正在使用Sails和Waterline进行模型关联,但我不确定如何修复在尝试更新PageChild对象时收到的此错误Mysql 无法添加或更新子行:外键约束失败约束`PageChild\u Page\u Id\u fk`外键(`PageId`)引用`Page`(`Id`),mysql,sails.js,waterline,Mysql,Sails.js,Waterline,我正在使用Sails和Waterline进行模型关联,但我不确定如何修复在尝试更新PageChild对象时收到的此错误 module.exports = { tableName: 'Page', adapter: 'mysql', autoCreatedAt: false, autoUpdatedAt: false, attributes: { Id: {type: 'integer', autoIncrement: true, pri
module.exports = {
tableName: 'Page',
adapter: 'mysql',
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
Id: {type: 'integer', autoIncrement: true, primaryKey: true},
pageChildren: {
collection: 'PageChild',
via: 'Page'
}
},
};
module.exports = {
tableName: 'PageChild',
adapter: 'mysql',
attributes: {
Id: {type: 'integer', autoIncrement: true, primaryKey: true},
Page: {
model: 'Page',
columnName: 'PageId'
}
}
};
模型关联对于从页面对象填充pageChildren或从任何pageChildren返回页面对象都非常有效。但是,我在尝试创建或更新PageChild对象时遇到了这个外键问题
module.exports = {
tableName: 'Page',
adapter: 'mysql',
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
Id: {type: 'integer', autoIncrement: true, primaryKey: true},
pageChildren: {
collection: 'PageChild',
via: 'Page'
}
},
};
module.exports = {
tableName: 'PageChild',
adapter: 'mysql',
attributes: {
Id: {type: 'integer', autoIncrement: true, primaryKey: true},
Page: {
model: 'Page',
columnName: 'PageId'
}
}
};
在mysql数据库中,页面表具有“Id”属性,而PageChild表具有“Id”和“PageId”属性。错误是不言自明的:
foreign key constraint fails CONSTRAINT `PageChild_Page_Id_fk` FOREIGN KEY (`PageId`) REFERENCES `Page` (`Id`)
规则是,只能在子表中添加或更新父表中已经存在的值。因此,在插入时,请确保您试图在子表中插入的值已存在于父表中。错误是不言自明的:
foreign key constraint fails CONSTRAINT `PageChild_Page_Id_fk` FOREIGN KEY (`PageId`) REFERENCES `Page` (`Id`)
规则是,只能在子表中添加或更新父表中已经存在的值。因此,在插入时,请确保您试图在子表中插入的值已存在于父表中。这意味着您在子行上添加或更新的父ID必须存在于父表中 因此,此约束意味着您不能在
PageId=50的PageChild
中插入一行,如果Page
中没有id
值为50的行
例如,如果要创建新页面,必须首先在页面
表中创建一个条目,然后检索它的id
值,只有这样,您才能开始使用前面创建的页面的id向PageChild
表中插入内容。这意味着您在子行上添加或更新的父id
表中必须存在
因此,此约束意味着您不能在PageId=50的PageChild
中插入一行,如果Page
中没有id
值为50的行
例如,如果要创建一个新页面,您必须首先在页面
表中创建一个条目,然后检索它的id
值,只有这样,您才能开始使用前面创建的页面
的id向PageChild
表中插入内容