This is very old question, but it is still linked by Symfony (now 6.2), so I will give it quick update as this cost me about month of fighting with two entities due to its impreciseness.
The solution to all my problems was this little thing:
#[ORM\Table(schema: 'name_of_database')]
add this attribute to your entity and voilà - it will now use this database name when generating SQL query for this entity. But this is basically hardcoding the name of database for this entity - it won't change in different environments (for example on tests or different setup).
To fix this I've added new listener to Doctrine event loadClassMetadata, which changes schema for selected entities when env variable is changes to test:
namespace App\EventListener;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
use Doctrine\ORM\Events;
#[AsDoctrineListener(event: Events::loadClassMetadata, priority: 500)]
class DoctrineListener
{
public function loadClassMetadata(LoadClassMetadataEventArgs $event): void
{
if ('test' !== ($_ENV['APP_ENV'] ?? false)) {
return;
}
$meta = $event->getClassMetadata();
if (property_exists($meta, 'table') && isset($meta->table['schema'])) {
$meta->table['schema'] .= '_test';
}
if (!property_exists($meta, 'associationMappings')) {
return;
}
// ManyToMany tables
foreach ($meta->associationMappings as $i => $associationMapping) {
if (!isset($associationMapping['joinTable']['schema'])) {
continue;
}
$meta->associationMappings[$i]['joinTable']['schema'] .= '_test';
}
}
}
With this you could also have dynamic schema - change per setup if needed. Hope it helps.