symfony2 Doctrine删除一个对象数组

时间:2014-02-10 12:30:46

标签: php symfony doctrine

我想从数据库中删除与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语句时,它运行得很好。

4 个答案:

答案 0 :(得分:26)

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

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

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

$em->flush();

答案 1 :(得分:3)

您也可以使用以下内容:

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

请注意,使用PropelPropelBundle时,PropelObjectCollection会实现delete()功能,因此您无需手动执行此循环。

答案 2 :(得分:1)

您还可以使用原则查询构建器delete方法。

public function deleteAllByUser(UserInterface $user)
{
    $query = $this->createQueryBuilder('related_entity')
        ->delete()
        ->andWhere('related_entity.user = :user')
        ->setParameter('user', $user)
        ->getQuery();

    return $query->execute();
}

答案 3 :(得分:-1)

如果你返回一个对象,你只需要写:

 ->findOneByUser,

你不需要一个foreach循环。如果你的返回是一个数组,那么你需要做->findByUser并写一个for循环:

foreach ($entities as $entity)
{
  //do something
}