Checking two columns duplicate in Doctrine2

♀尐吖头ヾ 提交于 2019-12-25 01:39:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!