Created
April 4, 2021 22:11
-
-
Save cesurapp/c8bedeb44c4a0294cb65696c17650112 to your computer and use it in GitHub Desktop.
Symfony Doctrine Table Add Prefix
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 | |
namespace App\Listener; | |
use Doctrine\ORM\Event\LoadClassMetadataEventArgs; | |
use Doctrine\ORM\Mapping\ClassMetadataInfo; | |
class TablePrefixListener | |
{ | |
protected string $tablePrefix = ''; | |
public function __construct($tablePrefix) | |
{ | |
$this->tablePrefix = $tablePrefix.'_'; | |
} | |
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void | |
{ | |
$classMetadata = $eventArgs->getClassMetadata(); | |
if (!$classMetadata->isInheritanceTypeSingleTable() || $classMetadata->getName() === $classMetadata->rootEntityName) { | |
$classMetadata->setPrimaryTable([ | |
'name' => $this->tablePrefix.$classMetadata->getTableName(), | |
]); | |
} | |
foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) { | |
if (ClassMetadataInfo::MANY_TO_MANY === $mapping['type'] && $mapping['isOwningSide']) { | |
$mappedTableName = $mapping['joinTable']['name']; | |
$classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->tablePrefix.$mappedTableName; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment