Symfony2 ManyToMany关系不链接2个实体 - Doctrine2尝试持久化反向实体

时间:2015-11-05 18:21:30

标签: symfony doctrine-orm many-to-many entity persist

晚上好,

我设计了我的应用程序,以便用户可以订阅多个事件,而一个事件可以有多个User类型的订阅者。

我选择在实体事件和实体用户之间创建一个ManyToMany关系来实现这一点。

更确切地说,Eve​​nt实体拥有该关系。

iisreset

我的用户实体是关系的反面。

class Event implements EventInterface
{
/**
 * @ORM\ManyToMany(targetEntity="FS\UserBundle\Entity\User", inversedBy="events")
 */
private $subscribers;
public function __construct()
{
    $this->subscribers = new \Doctrine\Common\Collections\ArrayCollection();
}

/*
** FYI my app logic is to persist the event so i addEvent($this) to $subscriber
*/

public function addSubscriber(\FS\UserBundle\Entity\User $subscriber)
{
    $this->subscribers[] = $subscriber;

    $subscriber->addEvent($this);

    return $this;
}

我将addSubscriber($ user)添加到新事件中。然后我将EventForm的数据发送给该控制器:

class User implements UserInterface
{
/**
 * @ORM\ManyToMany(targetEntity="FS\EventBundle\Entity\Event", mappedBy="subscribers")
 */
private $events;

public function __construct()
{
    $this->events = new \Doctrine\Common\Collections\ArrayCollection();
}

public function addEvent(\FS\EventBundle\Entity\Event $event)
{
    $this->events[] = $event;

    return $this;
}
...

当我坚持事件时,用户没有反映任何更改,我得到以下异常:通过未配置的关系'FS \ UserBundle \ Entity \ User#events'找到新实体级联实体[user]的持久化操作。

为什么Doctrine2会在这种情况下尝试重新保留用户?

1 个答案:

答案 0 :(得分:0)

试试这个:

class Event implements EventInterface
{
    /**
     * @ORM\ManyToMany(targetEntity="FS\UserBundle\Entity\User", inversedBy="events", cascade={"persist"})
     */
    private $subscribers;