Doctrine, delete the collection?

I need to delete a collection using Doctrine with Symfony2.

So, I retrieve all such objects:

$comments = $em->getRepository('ProjectApplicationBundle:Comment')->findBy(array('user_id' => $user_id)); 

This way I can get a lot of comments.

How can I delete these comments? Simple $em->remove($comments) does not work.

Do I need to quote comments and delete each item? Better to write a request directly? Any better ways? Thanks

+6
source share
3 answers

You need to put them in a loop and delete each

 foreach ($comments as $cm) { $em->remove($cm); } $em->flush(); 

Just in case for the future, if you have a OneToMany relationship for the field and you want to delete all related objects with 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(); 
+6
source

Here is a single line:

 $comments->forAll(function($key, $entity) { $this->em->remove($entity); }); 

Of course, don't forget $em->flush(); afterwards.

0
source

A single line should look like this:

 $comments->forAll(function($key, $entity) { $this->em->remove($entity); return true; }); 

The rest is good!

0
source

All Articles