Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2 Doctrine delete an array of objects

I would like to delete all the records from database matching a particular user_id in Symfony2.

$em = $this->getDoctrine()->getManager();
$user_service = $em->getRepository('ProjectTestBundle:UserService')
->findByUser($this->getUser()->getId());

This might return a few matching objects, so when I run:

$em->remove($user_service);
$em->flush();

an error occurs:

EntityManager#remove() expects parameter 1 to be an entity object, array given.

How do I remove all records (objects) matching a particular condition? Btw, when I run an equivalent sql statement in mysql, it works perfectly.

like image 416
Davit Avatar asked Feb 10 '14 12:02

Davit


2 Answers

Why don't you just loop through the objects array?

$user_services = $em->getRepository('ProjectTestBundle:UserService')
->findByUser($this->getUser()->getId());

foreach ($user_services as $user_service) {
    $em->remove($user_service);
}

$em->flush();
like image 75
Markus Kottländer Avatar answered Oct 23 '22 10:10

Markus Kottländer


You could also use something like this:

$user_services = $em->getRepository('ProjectTestBundle:UserService')->findByUser($this->getUser()->getId());
array_walk($user_services, array($this, 'deleteEntity'), $em);
$em->flush();

Then add this method in your controller:

protected function deleteEntity($entity, $key, $em)
{
    $em->remove(entity);
}

Or simply use:

$user_services = $em->getRepository('ProjectTestBundle:UserService')->findByUser($this->getUser()->getId());
$this->deleteEntities($em, $user_services);
$em->flush();

...

protected function deleteEntities($em, $entities)
{
    foreach ($entities as $entity) {
        $em->remove($entity);
    }
}

Note that when using Propel and the PropelBundle, the PropelObjectCollection implements a delete() function so you don't have to do this loop by hand.

like image 5
COil Avatar answered Oct 23 '22 10:10

COil