0
晚上好,Symfony2的多對多關係沒有鏈接2名的實體 - Doctrine2試圖堅持逆實體
我設計的應用程序,使用戶可以訂閱多個事件和事件可以有類型用戶的多個用戶。
我選擇在實體Event和實體User之間創建ManyToMany關係來實現此目的。
更準確地說,Event實體擁有該關係。
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會在這種情況下嘗試重新保留用戶?
我嘗試添加級聯= {「堅持」},但錯誤是一樣的,你有其他想法? – Louis
http://docs.doctrine-project.org/en/latest/reference/working-with-associations.html,你需要添加一些方法,我會盡快更新我的答案 – smarber