我有3个实体:人,隶属关系和人员关系。
在我的表单中,我会将每个联盟显示为已选中的复选框。
当用户取消选中该复选框并单击“提交”时,应该从PersonAffiliation表中删除此关联。
问题是,当我提交而不取消选中时,我的数据会重复。 示例:aff1和aff2。当检查并提交时,我将获得aff1 aff1 aff2 aff2。 同样,如果我取消选中aff2,那么我将拥有aff1 aff1。
错误可能在使用原则的某处:
以下是我如何管理:
Entity Persom
@ORM\OneToMany(targetEntity="PersonAffiliation", mappedBy="person", cascade={"persist", "remove"})
protected $affiliations;
实体联盟:
@ORM\OneToMany(targetEntity="PersonAffiliation", mappedBy="affiliation")
protected $person_affiliations;
实体PersonAffiliation
@ORM\ManyToOne(targetEntity="Person", inversedBy="affiliations")
@ORM\JoinColumn(name="person_id", referencedColumnName="id")
protected $person;
@ORM\ManyToOne(targetEntity="Affiliation", inversedBy="person_affiliations")
@ORM\JoinColumn(name="affiliation_id", referencedColumnName="id")
protected $affiliation;
关于如何解决这个问题的想法?
谢谢。
编辑:
Cotroller部分:
foreach( $enquiry->getAffiliations() as $aff )
{
$pAff = new PersonAffiliation();
$pAff->setPersonId( $person->getId() );
$pAff->setAffiliationId( $aff->getAffiliation()->getId() );
$pAff->setPerson( $person );
$pAff->setAffiliation( $aff->getAffiliation() );
$em->persist($pAff);
$em->flush();
}
表格部分:
public function buildForm(FormBuilder $builder, array $options)
{
$person = $this->person;
$user = $this->user;
$builder->add('firstname', 'text');
$builder->add('middlename', 'text', array('required'=>false));
$builder->add('lastname', 'text');
$builder->add('sex', 'choice', array( 'choices' => array('m' => 'Male', 'f' => 'Female'),
'required' => true,
'multiple' => false,
'expanded' => true));
$builder->add('email', 'text', array('required'=>false));
if( $this->addAffiliations ) {
$builder->add('affiliations', 'entity', array(
'label' => 'Athor\'s affiliations',
'class' => 'SciForumVersion2Bundle:PersonAffiliation',
'query_builder' => function($em) use ($person, $user){
return $em->createQueryBuilder('pa')
->where('pa.person_id = :pid')
->setParameter('pid', $person->getId());
},
'property' => 'affiliation',
'multiple' => true,
'expanded' => true,
));
}
}
答案 0 :(得分:1)
在Person实体中:
/**
* @ORM\ManyToMany(targetEntity="Affiliation", inversedBy="people")
* @ORM\JoinTable(name="PersonAffiliation")
*/
protected $affiliations;
在Affiliation实体中:
/**
* @ORM\ManyToMany(targetEntity="Person", mappedBy="affiliations")
*/
protected $people;
答案 1 :(得分:0)
您在foreach的每次迭代中都创建了$em->flush()
。它应该在foreach结束之后完成吗?
此外,您可以使用ManyToMany
关系。