无法添加或更新子行:外键约束失败CONSTRAINT`PageChild_Page_Id_fk` FOREIGN KEY(`PageId`)REFERENCES`Page`(`Id`)

时间:2017-06-15 16:00:15

标签: mysql sails.js waterline

我使用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表有一个" Id" PageChild表具有" Id"和" PageId"属性。

2 个答案:

答案 0 :(得分:2)

错误是不言自明的:

foreign key constraint fails CONSTRAINT `PageChild_Page_Id_fk` FOREIGN KEY (`PageId`) REFERENCES `Page` (`Id`)

规则是,您只能添加或更新子表中已存在于父表中的值。因此,在插入时,请确保您尝试在子表中插入的值已存在于父表中。

答案 1 :(得分:1)

这意味着您在子行上添加或更新的ParentId需要存在于Parent表中。

因此,如果PageChild中的行没有PageId = 50,则此约束意味着您无法在Page中使用id插入行值为50。

例如,如果要创建新页面,则必须先在Page表中创建一个条目,然后检索它的id值,然后才能开始插入PageChild表使用您之前创建的Page的ID。

相关问题