Doctrine query: delete with restriction
I am trying to delete only x objects with a delete request from Doctrine. And since there is no LIMIT in the doctrine, we should instead use $ query-> setMaxResults ($ limit). I am using Symfony2.
However, it doesn't work with the following query (with or without $ query-> setMaxResults ($ limit), it removes everything, not removes the first $ limit entities).
$limit = 10;
$query = $entityManager->createQuery(
'DELETE FROM MyProject\Bundle\MyBundle\Entity\MyEntity myEntity
WHERE myEntity.cost = 50'
)
$query->setMaxResults($limit);
$query->execute();
+3
source to share
1 answer
One solution that works is to use native SQL with Doctrine (instead of DQL).
$limit = 10;
$sql = 'DELETE FROM my_entity
WHERE cost = 50
LIMIT ' . $numberOfDeletion;
$entityManager->getConnection()->prepare($sql);
$stmt = $entityManager->getConnection()->prepare($sql);
$stmt->execute();
+1
source to share