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.
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();
                        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.
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