Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine query: delete with limit

I am trying to delete only x objects with a delete query from Doctrine. And since there is no LIMIT in doctrine, we should use $query->setMaxResults($limit) instead. I am using Symfony2.

However it does not work with the following query (with or without $query->setMaxResults($limit), it delete everything instead of deleting the $limit first entities).

$limit = 10;
$query = $entityManager->createQuery(
        'DELETE FROM MyProject\Bundle\MyBundle\Entity\MyEntity myEntity
         WHERE myEntity.cost = 50'
    )
$query->setMaxResults($limit);
$query->execute();
like image 579
msusplugas Avatar asked Nov 10 '22 03:11

msusplugas


1 Answers

One solution that works is to use native SQL with Doctrine like this (instead of DQL).

$limit = 10;
$sql    = 'DELETE FROM my_entity
           WHERE cost = 50
           LIMIT ' . $limit;
$stmt = $entityManager->getConnection()->prepare($sql);
$stmt->execute();
like image 195
msusplugas Avatar answered Nov 15 '22 08:11

msusplugas