1

我已经仔细阅读了Doctrine 文档,但是我无法在 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"}

对列定义似乎没有效果。错误在哪里?

4

1 回答 1

0

您应该首先阅读这部分文档

我建议从 User 实体中删除 @JoinTable。

仍然在您的用户实体中,您应该这样做:

public function addAttachment(Attachment  $attachment)
{
    $attachment->addUser($this); // synchronously updating inverse side
    $this->attachments[] = $attachment;
    return $this;
}

我的回答是假设您实际上希望您的 Attachment 实体成为您的拥有方,而您的 User 实体成为您的反方。

于 2012-07-23T21:16:51.373 回答