无法添加或更新子行:外键约束失败 CONSTRAINT `PageChild_Page_Id_fk` FOREIGN KEY (`PageId`) REFERENCES `Page` (`Id`)
Cannot add or update a child row: a foreign key constraint fails CONSTRAINT `PageChild_Page_Id_fk` FOREIGN KEY (`PageId`) REFERENCES `Page` (`Id`)
我正在为我的模型关联使用 Sails 和 Waterline,但我不确定该怎么做才能修复我在尝试更新 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'
}
}
};
模型关联非常适合从 Page 对象填充 pageChildren 或从任何 pageChildren 返回 Page 对象。但是,我在尝试创建或更新 PageChild 对象时遇到了这个外键问题。
在 mysql 数据库中,Page table 有一个 "Id" 属性,而 PageChild table 有 "Id" 和 "PageId" 属性.
错误不言自明:
foreign key constraint fails CONSTRAINT `PageChild_Page_Id_fk` FOREIGN KEY (`PageId`) REFERENCES `Page` (`Id`)
规则是,您只能在父 table 中已经存在的子 table 中添加或更新值。因此,在插入时,请确保您尝试插入子项 table 的值已存在于父项 table.
这意味着您在子行上添加或更新的 ParentId
需要存在于 Parent
table 上。
因此,此约束意味着如果 Page
中没有具有 [=15] 的行,则无法将行插入 PageChild
中 PageId = 50
=] 值为 50.
例如,如果你想创建一个新页面,你必须先在 Page
table 中创建一个条目,然后检索它的 id
值,然后才能您开始使用您之前创建的 Page
的 ID 向 PageChild
table 中插入内容。
我正在为我的模型关联使用 Sails 和 Waterline,但我不确定该怎么做才能修复我在尝试更新 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'
}
}
};
模型关联非常适合从 Page 对象填充 pageChildren 或从任何 pageChildren 返回 Page 对象。但是,我在尝试创建或更新 PageChild 对象时遇到了这个外键问题。
在 mysql 数据库中,Page table 有一个 "Id" 属性,而 PageChild table 有 "Id" 和 "PageId" 属性.
错误不言自明:
foreign key constraint fails CONSTRAINT `PageChild_Page_Id_fk` FOREIGN KEY (`PageId`) REFERENCES `Page` (`Id`)
规则是,您只能在父 table 中已经存在的子 table 中添加或更新值。因此,在插入时,请确保您尝试插入子项 table 的值已存在于父项 table.
这意味着您在子行上添加或更新的 ParentId
需要存在于 Parent
table 上。
因此,此约束意味着如果 Page
中没有具有 [=15] 的行,则无法将行插入 PageChild
中 PageId = 50
=] 值为 50.
例如,如果你想创建一个新页面,你必须先在 Page
table 中创建一个条目,然后检索它的 id
值,然后才能您开始使用您之前创建的 Page
的 ID 向 PageChild
table 中插入内容。