Skip to content

Instantly share code, notes, and snippets.

@cesurapp
Created April 4, 2021 22:11
Show Gist options
  • Save cesurapp/c8bedeb44c4a0294cb65696c17650112 to your computer and use it in GitHub Desktop.
Save cesurapp/c8bedeb44c4a0294cb65696c17650112 to your computer and use it in GitHub Desktop.
Symfony Doctrine Table Add Prefix
<?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