【问题标题】:Cannot add or update a child row: a foreign key constraint fails CONSTRAINT `PageChild_Page_Id_fk` FOREIGN KEY (`PageId`) REFERENCES `Page` (`Id`)无法添加或更新子行:外键约束失败 CONSTRAINT `PageChild_Page_Id_fk` FOREIGN KEY (`PageId`) REFERENCES `Page` (`Id`)
【发布时间】:2017-06-15 16:00:15
【问题描述】:

我正在将 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 db 中,Page 表具有“Id”属性,而 PageChild 表具有“Id”和“PageId”属性。

【问题讨论】:

    标签: mysql sails.js waterline


    【解决方案1】:

    错误是不言自明的:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2020-10-04
        相关资源
        最近更新 更多