为了账号安全,请及时绑定邮箱和手机立即绑定

跳过数据库中存在的实体

跳过数据库中存在的实体

PHP
至尊宝的传说 2021-07-08 14:01:44
我有需要在 db 中导入的 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 时,它总是导入所有值,而不应该像我提到的那样。
查看完整描述

1 回答

?
慕妹3242003

TA贡献1824条经验 获得超6个赞

请查看代码中的注释以了解更改的内容以及原因

基本上,您将 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 文件的人那里,然后要求正确地做它!!!


查看完整回答
反对 回复 2021-07-16
  • 1 回答
  • 0 关注
  • 189 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信