我在Symfony工作 - 当我执行删除用户的操作时,我收到以下错误消息:
[Semantical Error] line 0, col 7 near 'WHERE u.id =': Error: Class 'WHERE' is not defined.
500 Internal Server Error - QueryException
1 linked Exception:
QueryException »
1/2 QueryException: DELETE WHERE u.id = :id
2/2 QueryException: [Semantical Error] line 0, col 7 near 'WHERE u.id =': Error: Class 'WHERE' is not defined.
管理控制器
/**
* @Route("/admin/user/delete/{id}", name="admin_user_delete")
* @Template
*/
public function deleteAction($id)
{
$dispatcher = $this->container->get('event_dispatcher');
$this->get('users')->delete($id);
// create the user event and dispatch it
$event = new UserEvent($id);
$dispatcher->dispatch(UserEvents::USER_DELETED, $event);
$this->get('session')->getFlashBag()->add('notice-success', 'User deleted successfully.');
return $this->redirect($this->generateUrl('admin_user_list'));
}
User.php服务
public function delete($id)
{
$this->repository->delete($id);
}
用户存储库
public function delete($id)
{
$qb = $this->getEntityManager()->createQueryBuilder('u');
$qb->delete()
->andWhere($qb->expr()->eq('u.id', ':id'))
->setParameter(':id', $id)
->getQuery()
->getResult();
}
答案 0 :(得分:1)
使用查询构建器删除用户的方法
public function delete($id)
{
$qb = $this->getEntityManager()->createQueryBuilder();
return $qb->delete('Bundle:User', 'u')
->where('u.id = :id'))
->setParameter('id', $id)
->getQuery()
->getResult();
}
如何使用内置ORM删除用户
public function delete($id) {
// get access to the entity manager
$em = $this->getEntityManager();
// get the user from the repository by id
// previous version, slightly slower as it executes a query
// $user = $em->getRepository('Bundle:User')->find($id);
// Cerads method I just found out about myself, even better version!
// this doesn't execute a query but gets a reference to the user object
// and sets the id
$user = $em->getReference('Bundle:User', $id);
// use built in methods to delete the user
$em->remove($user);
// update the database with the change
$em->flush();
}
答案 1 :(得分:0)
正如Jared Farrish上面所说,你在setParameter
电话中不需要冒号。
应该是:
->setParameter('id', $id)