Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine, remove collection?

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

like image 865
Clément Andraud Avatar asked Mar 13 '14 13:03

Clément Andraud


3 Answers

One-liner should be like this:

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

Rest is good!

like image 152
Max Kaps 4bis.nl Avatar answered Nov 03 '22 01:11

Max Kaps 4bis.nl


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.

like image 33
Erdal G. Avatar answered Nov 02 '22 23:11

Erdal G.


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();
like image 8
Javad Avatar answered Nov 03 '22 01:11

Javad