首页 > 解决方案 > 跳过数据库中存在的实体

问题描述

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

标签: phpsymfonyif-statementdoctrine-ormentity

解决方案


请查看代码中的注释以了解发生了什么变化以及原因

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


推荐阅读