如何使用symfony2中的查询删除记录

时间:2014-02-19 07:36:56

标签: symfony twig

我是symfony2的新手,我在使用查询构建器删除对象时陷入控制器的某些部分,如果我在某处出错,请帮助我

控制器

public function deleteAction(Request $request){
    $tracks = $this->getDoctrine()
    ->getRepository('TcPlayerBundle:TcTracks')
    ->find($request->get('id'))
    /*->delete($id);*/
    ->createQuery('DELETE from TcPlayerBundle:TcTracks t WHERE t.id =:id');


    return $this->render('TcPlayerBundle:Default:all.html.twig',array(
        'tracks' => $tracks
    ));
}

我收到错误

Call to undefined method Tc\PlayerBundle\Entity\TcTracks::createQuery() in /opt/lampp/htdocs/tunecookies/trunk/src/Tc/PlayerBundle/Controller/DefaultController.php line 163

帮助我,谢谢

1 个答案:

答案 0 :(得分:2)

来自symfony docs,在您的控制器操作中:

$track = $this->getDoctrine()
    ->getRepository('TcPlayerBundle:TcTracks')
    ->findOneById($request->get('id'));
$em = $this->getDoctrine()->getManager();
$em->remove($track);
$em->flush();

或者,如果您确实需要,请通过查询构建器,例如:

$deleteQuery = $this->getDoctrine()
     ->getManager()
     ->createQueryBuilder('d')
     ->delete('TcPlayerBundle:TcTracks', 'd')
     ->where('d.id = ' . $request->get('id'))->getQuery();
$deleted = $deleteQuery->getResult();