我已经仔细阅读了Doctrine documentation,但我无法在2.2版本中建立多对多的双向关系。 这是代码:
附件实体
/**
* @ORM\Entity
* @ORM\Table(name="attachment")
* @ORM\HasLifecycleCallbacks
*/
class Attachment
{
...
/**
* @var ArrayCollection $users
*
* @ORM\ManyToMany(targetEntity="User", inversedBy="attachments", cascade={"persist"})
* @ORM\JoinTable(name="users_attachments")
**/
private $users;
...
/**
* Get associated users
*
* @return ArrayCollection
*/
public function getUsers()
{
return $this->users;
}
/**
* Add User to this Attachment
*
* @return User
*/
public function addUser(User $user)
{
$this->users[] = $user;
return $this;
}
/**
* Add Users to this Attachment
*
* @param ArrayCollection
*/
public function setUsers($users)
{
$this->users = $users;
}
用户实体
/**
* @ORM\Entity
* @ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
...
/**
* @var \Doctrine\Common\Collections\ArrayCollection $attachments
*
* @ORM\ManyToMany(targetEntity="Attachment", mappedBy="users", cascade={"persist", "remove"})
* @ORM\JoinTable(name="users_attachments")
**/
private $attachments;
...
/**
* Add an Attachment
*
* @param ArrayCollection $attachments
* @return User
*/
public function setAttachments(ArrayCollection $attachments)
{
$this->attachments = $attachments;
return $this;
}
/**
* Add an Attachment
*
* @param Attachment $attachment
* @return User
*/
public function addAttachment(Attachment $attachment)
{
$this->attachments[] = $attachment;
return $this;
}
public function getAttachments()
{
return $this->attachments;
}
通过此设置,我可以使以下工作(即附件和用户正确存储):
$attachment = $this->getDoctrine()
->getRepository('MyBundle:Attachment')
->find($attachment_id);
$attachment->addUser($this->getDoctrine()
->getRepository('MyBundle:User')
->find($user_id))
$em->persist($attachment);
$em->flush();
但是,我还需要使用以下代码(即,它不会触发错误,但不会更新关系):
$user = $this->getDoctrine()
->getRepository('MyBundle:User')
->find($user_id);
$user->addAttachment($this->getDoctrine()
->getRepository('MyBundle:Attachment')
->find($attachment_id))
$em->persist($user);
$em->flush();
如果在添加附件后检查用户实体,我可以看到实体已正确存储在内存中,但是当刷新EM时,不会发出任何查询。
应用属性
cascade={"persist"}
到列定义似乎没有效果。错误在哪里?
答案 0 :(得分:0)
您应该先阅读this part of the documentation。
我建议从用户实体中删除@JoinTable。
仍然在您的用户实体中,您应该这样做:
public function addAttachment(Attachment $attachment)
{
$attachment->addUser($this); // synchronously updating inverse side
$this->attachments[] = $attachment;
return $this;
}
我的回答是假设您实际上希望您的附件实体是您自己的一方而您的用户实体是您的反面。