How To TRUNCATE TABLE With Symfony And Doctrine?

There are two possibilities for bulk deletes with Doctrine. You can either issue a single DQL DELETE query or you can iterate over results removing them one at a time.

Example of single DQL Delete query:
 $em = $this->getDoctrine()->getManager();
 $em->createQuery('DELETE FROM AppBundle\Entity\Customer')->execute();

It is very simple to truncate or empty the table from mysql using Symfony and Doctrine.

Note: If you have relations you should be careful to handle the linked entities.
Ref: http://doctrine-orm.readthedocs.org/en/latest/reference/batch-processing.html#dql-delete

Comments



  1. I assume that I need to build a native query to truncate a table using Doctine 2.

    $emptyRsm = new \Doctrine\ORM\Query\ResultSetMapping();
    $sql = 'TRUNCATE TABLE Article';
    $query = em()->createNativeQuery($sql, $emptyRsm);
    $query->execute();

    This gives the error

    SQLSTATE[HY000]: General error

    What do I need to change to my code to make this work?

    ReplyDelete

Post a Comment

Popular Posts