Good evening,
I designed my application so that a User can subscribe to multiple events and an Event can have multiple subscribers of type User.
I opted to create a ManyToMany relationship between an entity Event and an entity User to achieve this.
More precisely, the Event entity owns the relation.
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;
}
My User entity is the inverse side of the relation.
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;
}
...
I addSubscriber($user) to a new Event. Then i send the Event with my EventForm's data to this controller :
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);
}
When i persist the Event, the User doesn't reflect any changes and i get the following exception : A new entity was found through the relationship 'FS\UserBundle\Entity\User#events' that was not configured to cascade persist operations for entity [user].
Why would Doctrine2 try to re-persist the User in this case ?