Doctrine - delete all entities

Viewed 8303

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);
}
2 Answers
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);
}

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?

Related