防止多对一关系中的重复

时间:2018-06-21 18:20:16

标签: symfony doctrine-orm orm

使用该学说,我有两个实体,一个叫做Institution,另一个叫做Location。每个机构都有一个位置,但是两个或多个机构可以具有相同的位置。它们由Institution中的外键链接。

机构:

/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string")
 */
private $name;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Location", cascade={"persist"})
 */
private $location;

位置:

/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", nullable=false)
 */
private $renderedLocation;

/**
 *
 * @ORM\Column(type="string", length=60, unique=true, nullable=false)
 */
private $placeId;

添加新机构后,系统会要求其提供该机构的位置,并在Google place API的帮助下保存renderedLocation和唯一的placeIdLocation的形式使用symfony形式嵌入为Institution的形式。

表格:

    $builder
        ->add('name')
        ->add('location', LocationType::class)

提交表单后,将保存新的Institution和新的Location

我想实现的是通过比较唯一的placeId来检查用户输入的位置是否已经在数据库中。在这种情况下,请将新的Institution连接到已经存在的Location。如果不是,请创建新的Institution和新的Location

我尝试使用Prevent duplicates in the database in a many-to-many relationship中所述的方法解决此问题,但是没有运气。即使这样做确实可行,在所有将来仍然使用事件侦听器似乎有些矫kill过正。关于如何处理此问题有什么想法?

编辑:我按照Khalid Junaid先生的建议进行了检查,并检查了表单数据是否重复。它有效,但我怀疑这是否是正确的方法。任何建议,不胜感激。

控制器:

    if ($form->isSubmitted() && $form->isValid()) {
        //....
        $user->addLinkedInstitution($institution);
        $institution = $form->getData();
        $placeId = $institution->getLocation()->getPlaceId();
        $existingLocation = $em->getRepository('App:Location')->checkDuplicate($placeId)->getQuery()->getOneOrNullResult();
        if ($existingLocation != null){
        $existingPlaceId = $existingLocation->getPlaceId();
        }
        else{
            $existingPlaceId = null;
        }
        if ($placeId == $existingPlaceId)
        {
            $institution->setLocation($existingLocation);
        }

0 个答案:

没有答案