首页 > 解决方案 > 完整性约束违规:1452 无法添加或更新子行:外键约束失败错误

问题描述

这是我的代码。它添加了一些记录。但在某些时候给了我错误。

foreach($data as $obj){

  if($obj && $obj->stateId && $obj->countryId) {
     MasterCity::create(array(
        'name' => $obj->name,
        'state_id' => $obj->stateId,
        'country_id' => $obj->countryId
    ));
  }
}

我收到 2 个错误:

 C:\ashish\backend\laravel-backend\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDOStatement.php:129
      Doctrine\DBAL\Driver\PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`blue_rickshaw`.`mast
er_cities`, CONSTRAINT `master_cities_state_id_foreign` FOREIGN KEY (`state_id`) REFERENCES `master_states` (`id`))")

  2   C:\ashish\backend\laravel-backend\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDOStatement.php:127
      PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`blue_rickshaw`.`master_cities`, CONSTRAIN
T `master_cities_state_id_foreign` FOREIGN KEY (`state_id`) REFERENCES `master_states` (`id`))")

标签: phplaravellaravel-5

解决方案


您正在尝试引用一个不存在的 state_id。

实际上,您需要在父表中插入一条记录,然后才能引用它


推荐阅读