Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DELETE query not working in DQL doctrine Symfony2

I am to delete a row based on ID, and i used this query to do the task:

 $em = $this->getDoctrine()->getManager();
    $query = $em->createQuery('DELETE buss from StreetBumbApiBundle:BussOwner buss WHERE buss.id = :bussId')
        ->setParameter("bussId", $bussId);
    $list = $query->getResult();

but i am getting this error:

{ "code": 500, "message": "[Semantical Error] line 0, col 7 near 'buss from StreetBumbApiBundle:BussOwner': Error: Class 'buss' is not defined." }

What is wrong i am doing?

like image 727
Geetika Avatar asked Jul 02 '15 06:07

Geetika


Video Answer


2 Answers

You could solve this easily by using the QueryBuilder:

$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$query = $qb->delete('StreetBumbApiBundle:BussOwner', 'buss')
            ->where('buss.id = :bussId')
            ->setParameter('bussId', "bussId")
            ->getQuery();

$query->execute();

BTW: If you replace getQuery with getDQL you can see how this translates into DQL (or getSQL)

What essentially is wrong in your method is the from in your Delete statement as delete in DQL looks like this:

$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
              'DELETE StreetBumbApiBundle:BussOwner buss 
               WHERE buss.id = :bussId')
            ->setParameter("bussId", $bussId);

$query->execute();

Also, I am not sure why you use $query->getResult(). What would be the expected result of a delete? $query->execute(); does the job.

Apart from that, if you don't do complex delete statements, and in your case you are deleting an Entity querying with an Id.

Why not:

$em = $this->getDoctrine()->getManager();
$em->remove($entity);

And therefore pass the Entity, not just the Id to your delete function?

like image 102
DerStoffel Avatar answered Sep 24 '22 00:09

DerStoffel


Alternative solution: your DQL is not a good one, try with this

 $em = $this->getDoctrine()->getManager();
 $query = $em->createQuery(
     'DELETE 
        StreetBumbApiBundle:BussOwner buss 
      WHERE 
        buss.id = :bussId'
      )
      ->setParameter("bussId", $bussId);

 $result = $query->execute();
like image 30
DonCallisto Avatar answered Sep 24 '22 00:09

DonCallisto