根据教义,我有两个实体,一个叫做
Institution
其中一个打电话来
Location
机构
.
机构:
/**
* @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;
添加新机构时,会询问该机构的位置,这将保存
renderedLocation
以及独一无二的
placeId
在googleplacesapi的帮助下。表格
位置
以…的形式嵌入
使用symfony表单。
$builder
->add('name')
->add('location', LocationType::class)
表格提交后,一个新的
机构
和一个新的
位置
已保存。
地点ID
. 如果是这种情况,连接新的
机构
到已经存在的
位置
机构
以及新的
位置
我尝试使用中描述的方法解决此问题
Prevent duplicates in the database in a many-to-many relationship
编辑
:我按照M 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);
}