2015-11-05 79 views
0

晚上好,Symfony2的多对多关系没有链接2名的实体 - Doctrine2试图坚持逆实体

我设计的应用程序,使用户可以订阅多个事件和事件可以有类型用户的多个用户。

我选择在实体Event和实体User之间创建ManyToMany关系来实现此目的。

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

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; 
} 

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

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; 
} 
... 

我添加了用户($ user)到一个新的事件。然后,我与我的EventForm的数据发送事件到该控制器:

private function processForm(EventInterface $event, array $parameters, $method = "PUT") 
{ 
    $form = $this->formFactory->create(new EventType(), $event, array('method' => $method)); 
    $form->submit($parameters, 'PATCH' !== $method); 

    $event = $form->getData(); 

    $validator = $this->container->get('validator'); 
    $listErrors = $validator->validate($event); 

    if ($form->isValid() && count($listErrors) === 0) { 
     $event->setAge(); 

     $this->om->persist($event); 
     $this->om->flush($event); 
    } 

当我坚持的情况下,用户并不反映任何变化和我得到以下异常:一个新的实体是通过关系找到'FS \ UserBundle \ Entity \ User#events'未配置为级联实体[用户]的持久操作。

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

回答

0

试试这个:

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

我尝试添加级联= {“坚持”},但错误是一样的,你有其他想法? – Louis

+0

http://docs.doctrine-project.org/en/latest/reference/working-with-associations.html,你需要添加一些方法,我会尽快更新我的答案 – smarber