Question

I need to delete all rows where the image_id = x applies like this

DELETE FROM  `ImageVoters` WHERE image_id =1

How do I do this using DQL?

Since im trying to delete several rows at once the remove() function won't work

EntityManager#remove() expects parameter 1 to be an entity object, array given.

 $em = $this->getDoctrine()->getManager();
 $query = $em->createQuery('SELECT u FROM GabrielUploadBundle:ImageVoters u WHERE u.image_id = 1');
 $db_imageactions = $query->getResult();
 $em->remove($db_imageactions);
 $em->flush();

This is the code that works

    $qb = $em->createQueryBuilder();
    $qb->delete('GabrielUploadBundle:ImageVoters', 'v')
        ->where($qb->expr()->eq('v.image_id', ':imageId'))
        ->setParameter('imageId', $current_imageId);

    $qb->getQuery()->execute();
Was it helpful?

Solution

You could create an ORM queryBuilder, to create a clean/safe query object by using internal orm methods

$qb->delete('My\Image\Namespace\ImageVoters', 'ivoter')
   ->where($qb->expr()->eq('ivoter.image_id', ':imageId')
   ->setParameter('imageId', 1);

$qb->getQuery()->execute();

OTHER TIPS

You can also execute any raw SQL like this:

$sql = "DELETE FROM ImageVoters WHERE image_id =".$image_id;
$q = $em->getConnection()->exec($sql);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top