跳过数据库中存在的实体

我有需要在 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 时,它总是导入所有值,而不应该像我提到的那样。


至尊宝的传说
浏览 190回答 1
1回答

慕妹3242003

请查看代码中的注释以了解更改的内容以及原因基本上,您将 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 文件的人那里,然后要求正确地做它!!!
打开App,查看更多内容
随时随地看视频慕课网APP