RKlina
RKlina

Reputation: 31

Cannot Delete User - QueryException: DELETE WHERE u.id = :id

I am working in Symfony - When I am performing an action to delete a user I am receiving the following error messages:

[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.

Admin Controller

 /**
 * @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 Service

public function delete($id)
{
    $this->repository->delete($id);
}

User Repository

public function delete($id)
{
    $qb = $this->getEntityManager()->createQueryBuilder('u');
    $qb->delete()
        ->andWhere($qb->expr()->eq('u.id', ':id'))
        ->setParameter(':id', $id)
        ->getQuery()
        ->getResult();
}

Upvotes: 0

Views: 188

Answers (2)

JacobW
JacobW

Reputation: 876

Method to delete a user with the query builder

public function delete($id)
{
    $qb = $this->getEntityManager()->createQueryBuilder();
    return $qb->delete('Bundle:User', 'u')
        ->where('u.id = :id'))
        ->setParameter('id', $id)
        ->getQuery()
        ->getResult();
}

How to delete a user using the built in 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();
}

Upvotes: 1

Jake Litwicki
Jake Litwicki

Reputation: 232

As Jared Farrish said above, you don't need the colon in the setParameter call.

Should be:

->setParameter('id', $id)

Upvotes: 0

Related Questions