且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel迁移-违反完整性约束:1452无法添加或更新子行:外键约束失败

更新时间:2023-12-01 08:55:46

您可能在inventories表中有一些记录,其中local_idcontents表中没有对应的id,因此会出现错误.您可以通过以下两种方法之一解决它:

You probably have some records in the inventories table with local_id that does not have corresponding id in the contents table, hence the error. You could solve it by one of the two ways:

  • 在关闭foreign_key_checks的情况下运行迁移.这将禁用现有行的外键约束(如果这就是您想要的). 此处
  • 仅插入在contents表中具有对应的id字段的那些记录.您可以使用INSERT INTO.. WHERE EXISTS查询将记录过滤掉,并仅插入那些记录.
  • Run the migration with foreign_key_checks turned off. This will disabled the foreign key constraints for the existing rows (if that's what you want). It's documented here
  • Insert only those records that have corresponding id field in contents table. You can use INSERT INTO.. WHERE EXISTS query to filter the records out, and insert only those records.