Я делаю нечто подобное в проекте с событиями, в которых есть участники, не похожие на ваши отношения между пользователем и страной.Я просто изложу процесс, и вы увидите, есть ли что-то, что вы делаете по-другому.
На Participant
сущности
/**
* @ManyToOne(targetEntity="Event", inversedBy="participants", fetch="LAZY")
* @JoinColumn(name="event_id", referencedColumnName="id", nullable="TRUE")
* @var Event
*/
protected $event;
На Event
сущности:
/**
* @OneToMany(targetEntity="Participant", mappedBy="event")
* @var \Doctrine\Common\Collections\ArrayCollection
*/
protected $participants;
Также в Event#__constructor
Я инициализирую так:
$this->participants = new \Doctrine\Common\Collections\ArrayCollection();
Вот как я обновляю событие:
public function update(Event $event, Event $changes)
{
// Remove participants
$removed = array();
foreach($event->participants as $participant)
{
if(!$changes->isAttending($participant->person))
{
$removed[] = $participant;
}
}
foreach($removed as $participant)
{
$event->removeParticipant($participant);
$this->em->remove($participant);
}
// Add new participants
foreach($changes->participants as $participant)
{
if(!$event->isAttending($participant->person))
{
$event->addParticipant($participant);
$this->em->perist($participant);
}
}
$event->copyFrom($changes);
$event->setUpdated();
$this->em->flush();
}
Методы в сущности Event
являются:
public function removeParticipant(Participant $participant)
{
$this->participants->removeElement($participant);
$participant->unsetEvent();
}
public function addParticipant(Participant $participant)
{
$participant->setEvent($this);
$this->participants[] = $participant;
}
Методы объекта Participant
:
public function setEvent(Event $event)
{
$this->event = $event;
}
public function unsetEvent()
{
$this->event = null;
}
ОБНОВЛЕНИЕ : метод isAttending
/**
* Checks if the given person is a
* participant of the event
*
* @param Person $person
* @return boolean
*/
public function isAttending(Person $person)
{
foreach($this->participants as $participant)
{
if($participant->person->id == $person->id)
return true;
}
return false;
}