我有5个实体:
这是模式:
一些细节:
我现在正在尝试使网络用户可以为作者(人)分配从属关系。为此,我有:
@ORM\OneToMany(targetEntity="PersonAffiliation", mappedBy="person", cascade={"persist", "remove"})
protected $affiliations;
@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;
@ORM\OneToMany(targetEntity="UserAffiliation", mappedBy="user")
protected $affiliations;
@ORM\ManyToOne(targetEntity="Person")
@ORM\JoinColumn(name="person_id", referencedColumnName="id")
protected $person;
@ORM\ManyToOne(targetEntity="User", inversedBy="affiliations")
@ORM\JoinColumn(name="user_id", referencedColumnName="id")
protected $user;
@ORM\ManyToOne(targetEntity="Affiliation", inversedBy="user_affiliations")
@ORM\JoinColumn(name="affiliation_id", referencedColumnName="id")
protected $affiliation;
在表单中,我正在执行下一个:
$builder->add('affiliations', 'entity', array(
'class' => 'SciForumVersion2Bundle:PersonAffiliation',
'query_builder' => function($em) use ($person){
return $em->createQueryBuilder('pa')->where('pa.person_id = :id')->setParameter('id', $person->getId());
},
'property' => 'affiliation',
'multiple' => true,
'expanded' => true,
));
但是,所有这些都无法正常运行。
说明:当我尝试添加新的从属关系时,仅为WebUser添加了该从属关系,而我无法通过表单将其链接到作者(人)。
您是否有关于如何解决此问题的想法,或者是一个很好的教程?
最佳答案
这应该在Entity1Controller.php中处理:
public function createAction(Request $request)
{
$securityContext = $this->get('security.context');
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(new Entity1Type()
,null,array('attr' => array('securitycontext' => $securityContext)));
$form->bind($request);
if ($form->isValid()){
$data = $form->getData();
$entity1id = $data->getId();
$entity2id = $data->getEntity2Id();
$entity1medicaid=$data->getMedicaidID();
$entity1=$em->getRepostiory('projectBundle:Entity1')->findOneById($entity1id);
$entity2=$em->getRepository('projectprojectBundle:Entity2')->findOneById($entity2id);
if (null === $entity1){
$entity1=new entity1();
$entity1->setEntity2id($entity2id);
$entity1->setID($entity1id);
}
if (null === $entity2){
$entity2=new entity2();
$entity2->setID($entity2id);
}
$em->persist($entity1);
$em->persist($entity2);
$em->flush();
return $this->redirect($this->generateUrl('entity1', array()));
}
return $this->render('Bundle:entity1:new.html.twig', array(
'form' => $form->createView()
,'attr' => array('securitycontext' => $securityContext
)
)
);
}
您可能还必须在关联映射中设置级联持久性。 Entity1.yml:
project\projectBundle\Entity\Entity1:
type: entity
table: entity1
repositoryClass: project\projectBundle\Entity\Entity1Repository
fields:
id:
type: bigint
id: true
generator:
strategy: AUTO
property:
type: string
length: 255
unique: true
manyToMany:
entity2:
targetEntity: entity2
mappedBy: entity1
cascade: ["persist"]
从理论上讲,symfony将使entity2处于幕后,使得不需要第二个null子句,但这总是令我感到困扰,因此我更愿意明确地这样做。