Created
January 11, 2023 12:41
-
-
Save florianorineveu/e8c2e92f292f7fa5845ee805b4909ada to your computer and use it in GitHub Desktop.
PHP Doctrine ORM - Proper truncate table with association/relation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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