php - 完整性约束违规: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`))")
解决方案
您正在尝试引用一个不存在的 state_id。
实际上,您需要在父表中插入一条记录,然后才能引用它
推荐阅读
- react-native - 未开发时无法在 Expo GO 上测试已发布的 Expo 项目
- angular - 为什么将角度依赖从 es2015 编译到 esm2015 会删除环境中的 html 标签?
- javascript - 进行“小于或等于”比较时,哪种方法更快?
- docker - 在通过我的 github 操作上的矩阵构建自定义图像之前,如何 docker pull 常用的 docker 图像?
- eslint - 带别名的 ESLint
- reporting-services - 使用 T-SQL 执行报表数据驱动订阅
- powershell - 在同一个powershell会话中一个接一个地执行两个命令
- python - 如何使用 FOR 循环生成对象?
- laravel - 为什么 laravel $request->file 返回 null?
- python - 如何使这个复杂的对象 JSON 可序列化?