php - 跳过数据库中存在的实体
问题描述
我有需要在数据库中导入的 json 数据。在持久化实体之前,我需要检查数据库中的两个字段值。如果它们存在,则跳过它们而不会引发错误,如果不存在,则仅创建缺少的那个。
$file = file_get_contents('file.json');
$jsonData = json_decode($file, true);
$check = $this->getMyRepository()->findOneBy([
'first_name' => $firstName,
'last_name' => $lastName
]);
foreach ($jsonData as $data) {
if ($check) {
continue;
} else {
$new = new MyEntity();
$new->setFirstName($data->getFirstName());
$new->setLastName($data->getLastName());
$this->em->persist($new);
}
}
}
$this->em->flush();
}
导入正在工作,但是当我触发 api 时,它总是导入所有值,并且不应该像我提到的那样。
解决方案
请查看代码中的注释以了解发生了什么变化以及原因
基本上,您将 json 文件转换为数组,因此您必须将$data
其作为数组寻址才能获取其值。
检查此人是否已存在的代码应该在循环内,因为您要在处理 json 文件中的人员集时检查每个人。
现在我们知道您的 JSON 文件真的没有帮助,也不真正配得上 JSON 的名字......
示例文件
{ "John Doe": "John Doe", "Jane Doe": "Jane Doe" }
代码需要是
$file = file_get_contents('file.json');
$jsonData = json_decode($file, true);
foreach ($jsonData as $data) {
// Split the single field into Firstname and lastname
$name = explode(' ', $data);
$exists = $this->getMyRepository()->findOneBy([
'first_name' => $name[0],
'last_name' => $name[1]
]);
if ($exists) {
// this person already in the database
// thats cool, just dont try and insert them again
continue;
} else {
// again in here you are getting data from an array
// called `$data` and not an entity with getters and setters
$new = new MyEntity();
$new->setFirstName($name[0]);
$new->setLastName($name[1]);
$this->em->persist($new);
}
}
}
$this->em->flush();
}
大警告此代码依赖于 JSON 数据文件,始终具有由空格分隔的名字和姓氏。 这是一件非常危险的事情
你真的应该回到创建这个 JSON 文件的人那里,然后要求正确地完成它!!!
推荐阅读
- javascript - 如何让 wepback 准备好用作导入的静态文件?
- windows - Discord JS npm install discord.js 问题
- postgresql - PostgreSQL 创建物化视图,根据字段和表列将 JSON 数组中的对象汇总到特定列中
- c++ - 如何将我的代码中的 int 变量作为二进制文件推送到文本文件中?
- python - 如何处理错误或再次尝试使用 python 发布到 pubsub 消息谷歌
- c# - 如何在 C# 中搜索 JSON 文件以查找特定值?
- kubernetes - Terraform GKE x509:由未知机构签署的证书
- javascript - 如何通过javascript更改`link`中的`href`
- c# - 使用 Datetime.UTC 设置西中非时间
- android - Ubuntu:Android Studio 中的虚拟设备