删除 symfony 2 中的错误

Ram*_*bay 1 symfony

我在删除方法中有一个错误,这是错误

EntityManager#remove() 期望参数 1 是一个实体对象,给定 NULL。

这是代码:

公共函数 supprimerAction($id){

$em = $this->get('doctrine')->getEntityManager();
$Livre=$em->getRepository('EspritBibBundle:Livre')->find($id);
$em->remove($Livre);
$em->flush();


return $this->render('EspritBibBundle:Livre:succes.html.twig',array('msg'=>'Suppression effectué avec succés'));
Run Code Online (Sandbox Code Playgroud)

}

sco*_*ico 5

尝试findOneById()和理查德说的一样,如果 $livre = null 则抛出异常

public function supprimerAction($id)
{
    $em = $this->getDoctrine()->getEntityManager();
    $livre = $em->getRepository('EspritBibBundle:Livre')->findOneById($id);

    if (!$livre) {
        throw $this->createNotFoundException('No livre found for id '.$id);
    } 

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

    return $this->render('EspritBibBundle:Livre:succes.html.twig',array('msg'=>'Suppression effectué avec succés'));
}
Run Code Online (Sandbox Code Playgroud)