I need to remove a collection with Doctrine with Symfony2.
So, i retrieve all objects like that :
$comments = $em->getRepository('ProjectApplicationBundle:Comment')->findBy(array('user_id' => $user_id));
So, with this, i can retrieve a lots of comments.
How can i remove these comments ? A simple $em->remove($comments)
don't work.
A need to loop comments and remove each element ? It is better to write the query directly ? Any better ways ? Thanks
One-liner should be like this:
$comments->forAll(function($key, $entity) {
$this->em->remove($entity);
return true;
});
Rest is good!
Here is a one-liner:
$comments->forAll(function($key, $entity) {$this->em->remove($entity); return true;});
Of course, don't forget the $em->flush();
afterwards.
You need to put them in loop and remove each one
foreach ($comments as $cm) {
$em->remove($cm);
}
$em->flush();
Just in case for future if you have OneToMany relation for a field and you want to remove all related objects to this or a specific object in the collection you can try
//entity class
/**
* @ORM\OneToMany(targetEntity="Target_Entity_Class",mappedBy="mapped_property")
* @var ArrayCollection
*/
$objects;
//...
public function removeObject(\Name\Space\To\Target\Entity $target)
{
$this->objects->removeElement($target);
}
And in your controller you can say
// assume $removed_objects_list is an array of related objects which you want to remove
$target_object = $em->getRepository('TargetEntity')->find($target_id);
foreach ($removed_objects_list as $object) {
$target_object->removeObject($object);
}
$em->flush();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With