问题
I wrote an API call that extracts .json file in MainTable.
In LangTable I have 3 languages and I am extracting the json data for every language.
Json data has key and locale field to populate.
To escape duplicate there should be no duplicated key<->locale values, so that should be checked for each key.
How to check that before persisting the database?
Code below works. Now I need to add logic I mentioned.
Can anybody help?
$file = file_get_contents('translation.json');
$jsonData = json_decode($file, true);
$findLanguage = $this->getLangTableRepository()->findAll();
foreach ( $findLanguage as $locale) {
foreach ($jsonData as $data) {
$newTranslation = new MainTable();
$newTranslation->setKey($data);
$newTranslation->setLocale($locale->getLocale());
$this->em->persist($newTranslation);
}
}
$this->em->flush();
dump('done!');die;
回答1:
You can use
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
UniqueEntity to add a constraint about being unique like so :
/**
* @ORM\Table(name="entity")
* @ORM\Entity(repositoryClass="App\MainBundle\Entity\EntityRepository")
* @UniqueEntity(fields={"attributeA"}, message="Attribute A already exists
*/
来源:https://stackoverflow.com/questions/56340135/checking-two-columns-duplicate-in-doctrine2