user3440145
user3440145

Reputation: 843

Reset (clear) a table in Doctrine ORM 2.5 and Symfony 3.4

Using Smyfony 3.4 and Doctrine ORM 2.5 (mySql) I am looking for a way to "reset" a table.

By reset I mean I want to delete all entries of that table and reset the autoincrement for the id column. Basically I want to get the initial state when the table was first created.

This should be used when re-filling a table from an update source.

There probably is a way to do this using the query builder but I couldn't figure it out yet.

Upvotes: 2

Views: 2094

Answers (1)

J. Almandos
J. Almandos

Reputation: 347

You can try something like:

$cmd = $em->getClassMetadata($className);
$connection = $em->getConnection();
$dbPlatform = $connection->getDatabasePlatform();
$connection->beginTransaction();
try {
    $connection->query('SET FOREIGN_KEY_CHECKS=0');
    $q = $dbPlatform->getTruncateTableSql($cmd->getTableName());
    $connection->executeUpdate($q);
    $connection->query('SET FOREIGN_KEY_CHECKS=1');
    $connection->commit();
}
catch (\Exception $e) {
    $connection->rollback();
}

And if you want to reset the auto-increment, just do:

$con->exec('ALTER TABLE ' . $cmd->getTableName() . ' AUTO_INCREMENT = 1;');

Upvotes: 1

Related Questions