Mysql 无法添加或更新子行:外键约束失败约束`PageChild\u Page\u Id\u fk`外键(`PageId`)引用`Page`(`Id`)

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

我正在使用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'
        }
    }
};
模型关联对于从页面对象填充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
表中插入内容