I'm trying to get some simple CRUD done with doctrine 2 but when it's time to update a record with one property set as an array collection I don't seem to get removeElement() to work as it's supposed to. I even tried doing it in this ridiculously ugly way:
foreach($entity->getCountries() as $c) {
$entity->getCountries()->removeElement($c);
$this->em->persist($entity);
$this->em->flush();
}
and it didn't work... Anyone knows how to handle this? I've asked for a solution to this in many different forms and haven't got a good response so far... seems there's lack of good examples of Doctrine 2 CRUD handling. I'll post more code at request.
Edit
//in user entity
/**
*
* @param \Doctring\Common\Collections\Collection $property
* @OneToMany(targetEntity="Countries",mappedBy="user", cascade={"persist", "remove"})
*/
private $countries;
//in countries entity
/**
*
* @var User
* @ManyToOne(targetEntity="User", inversedBy="id")
* @JoinColumns({
* @JoinColumn(name="user_id", referencedColumnName="id")
* })
*/
private $user;
New answer
In your countries entity, should you not have:
instead of inversedBy="id"?
Initial answer
You need to set the countries field in your entity as remove cascade. For example, on a bidirectional one to many relationship:
This way, when saving your entity, doctrine will also save changes in collections attached to your entity (such as countries). Otherwise you have to explicitly remove the countries you want to remove before flushing, e.g.
This is also valid for persist, merge and detach operations. More information here.
I do something similar in a project with Events which have participants not unlike your User/Country relationship. I will just lay out the process and you can see if there's anything you are doing differently.
On the
Participant
entityOn the
Event
entity:Also in
Event#__constructor
I initialize like this:Here is how I update an event:
The methods on the
Event
entity are:The methods on the
Participant
entity are:UPDATE: isAttending method