Doctrine - delete all entities
Asked Answered
S

2

5

I have problem with deleting all rows in database. I can't find out how to do it. I'm using Symfony and Doctrine. Somewhere I read, that it isn't possible "normal" way, but I can do it by DQL (createQuery), but I don't know syntax.

public function resetDatabase(EntityManagerInterface $em)
{
    $query = $em->createQuery('DELETE ???');
    $query->execute();

    return new Response('', Response::HTTP_OK);
}
Sulfide answered 2/9, 2018 at 20:2 Comment(1)
Please see the official documentation on that topic: doctrine-project.org/projects/doctrine-orm/en/2.6/reference/…Baguio
B
5
public function resetDatabase(EntityManagerInterface $em)
{
    $query = $em->createQuery(
          'DELETE FROM App\Entity\YourEntity e WHERE e.age > :ageparameter'
       )->setParameter('ageparameter', 10)->execute();

    return new Response('', Response::HTTP_OK);
}
Baeyer answered 26/8, 2020 at 12:57 Comment(0)
S
2

Ou... I have find out, how to do it.

/**
* @Route("/resetdatabase")
*/    
public function resetDatabase(EntityManagerInterface $em)
{
    $repository = $em->getRepository(MoneyDatabase::class);
    $entities = $repository->findAll();

    foreach ($entities as $entity) {
        $em->remove($entity);
    }
    $em->flush();

    return new Response('', Response::HTTP_OK);
}

But sometimes it must run twice, because somehow after 30 seconds entities return (but there are only compulsory columns, others are null). And after second run it disappear completely. It's strange, that it does only sometimes. Why it does at all?

Sulfide answered 3/9, 2018 at 14:9 Comment(3)
In case of thousands of entities, this will be super slow. Why remove one by one when you can do it all with a single command?Baguio
there will be only few entities (max. 10). And I wanted to find easiest way, how to do it (using my available skills).Sulfide
@JovanPerovic What is the single command for deleting all the entities?Baily

© 2022 - 2024 — McMap. All rights reserved.