Php 跳过数据库中存在的实体

Php 跳过数据库中存在的实体,php,symfony,if-statement,doctrine-orm,entity,Php,Symfony,If Statement,Doctrine Orm,Entity,我需要在数据库中导入json数据。 在持久化实体之前,我需要检查数据库中的两个字段值。 如果它们存在,则跳过它们而不抛出错误;如果不存在,则只创建缺少的一个 $file = file_get_contents('file.json'); $jsonData = json_decode($file, true); $check = $this->getMyRepository()->findOneBy([

我需要在数据库中导入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文件的人那里,然后要求他正确地完成它


将调用findOneBy的文件移动到foreach中,$firstName$lastName替换为$data->getFirstName()和$data->getLastName(),谢谢您的重播。无法工作,因为对string@Lite上的成员函数getFirsName()的调用让我们看看json文件的示例please@develops所以它在设置实体时也不起作用。非常感谢,但我的问题是,在我的json中,我只有一个名称列表,如array:97[“John Doe”=>“John Doe”“Jane Doe”=>“Jane Doe”]@RiggsFollyPlease你能给我们看一个真正的json文件的小样本吗?这是我在上面的评论中介绍的json文件的一部分@RiggsFolly{“John Doe”:“John Doe”,“Jane Doe”:“Jane Doe”}对不起,我复制了转储结果@RiggsFolly@develops在您的问题中,您说过导入除重复过滤器外有效。如果您的json文件确实与您在评论中发布的相同,那么您的导入无法工作,应该抛出“未知索引”类型的错误。