mardi 28 mai 2019

Skip entity that exist in database

I have json data that I need to import in db. I need to check two field values in database before persisting entity. If they exist to skip them without throwing an error and if not to create just the one missing.

 $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();
}

The import is working but when I trigger an api it always import all values and it shouldn't as I mentioned.

Aucun commentaire:

Enregistrer un commentaire