symfony2 Doctrine 删除对象数组

2022-08-30 23:01:07

我想从数据库中删除与Symfony2中特定user_id匹配的所有记录。

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

这可能会返回一些匹配的对象,因此当我运行时:

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

发生错误:

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

如何删除与特定条件匹配的所有记录(对象)?顺便说一句,当我在mysql中运行等效的sql语句时,它可以完美地工作。


答案 1

为什么不直接循环遍历对象数组?

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

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

$em->flush();

答案 2

您也可以使用类似如下的内容:

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

然后在控制器中添加此方法:

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

或者直接使用:

$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);
    }
}

请注意,当使用 和 时,将实现一个函数,因此您不必手动执行此循环。PropelPropelBundlePropelObjectCollectiondelete()


推荐