Skip to content

Instantly share code, notes, and snippets.

@florianorineveu
Created January 11, 2023 12:41
Show Gist options
  • Save florianorineveu/e8c2e92f292f7fa5845ee805b4909ada to your computer and use it in GitHub Desktop.
Save florianorineveu/e8c2e92f292f7fa5845ee805b4909ada to your computer and use it in GitHub Desktop.
PHP Doctrine ORM - Proper truncate table with association/relation
<?php
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Platforms\AbstractPlatform;
function truncateTable(
Connection $connection,
AbstractPlatform $databasePlatform,
string $entityName
): void
{
$classMetadata = $this->entityManager->getClassMetadata($entityName);
$tablesToTruncate = [$classMetadata->getTableName()];
foreach ($classMetadata->getAssociationMappings() as $associationMapping) {
if (array_key_exists('joinTable', $associationMapping)
&& array_key_exists('name', $associationMapping['joinTable'])
&& !in_array($associationMapping['joinTable']['name'], $tablesToTruncate)
) {
$tablesToTruncate[] = $associationMapping['joinTable']['name'];
}
}
$connection->executeQuery('SET FOREIGN_KEY_CHECKS=0');
foreach ($tablesToTruncate as $tableName) {
$connection->executeStatement($databasePlatform->getTruncateTableSQL($tableName));
}
$connection->executeQuery('SET FOREIGN_KEY_CHECKS=1');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment