Search code examples
doctrine-orm

Ignore a Doctrine2 Entity when running schema-manager update


I've got a Doctrine Entity defined that maps to a View in my database. All works fine, the Entity relations work fine as expected.

Problem now is that when running orm:schema-manager:update on the CLI a table gets created for this entity which is something I want to prevent. There already is a view for this Entity, no need to create a table for it.

Can I annotate the Entity so that a table won't be created while still keeping access to all Entity related functionality (associations, ...)?


Solution

  • Eventually it was fairly simple, I just had to subclass the \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand into my own CLI Command. In that subclass filter the $metadatas array that's being passed to executeSchemaCommand() and then pass it on to the parent function.

    Just attach this new subclassed command to the ConsoleApplication you are using in your doctrine cli script and done!

    Below is the extended command, in production you'll probably want to fetch the $ignoredEntities property from you config or something, this should put you on the way.

    <?php
    
    use Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand;
    use Doctrine\ORM\Tools\SchemaTool;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    use Symfony\Component\Console\Style\SymfonyStyle;
    
    class My_Doctrine_Tools_UpdateCommand extends UpdateCommand
    {
        protected $name = 'orm:schema-tool:myupdate';
    
        protected $ignoredEntities = array(
            'Entity\Asset\Name'
        );
    
        protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas, SymfonyStyle $ui)
        {
            /** @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */
            $newMetadata = [];
            foreach ($metadatas as $metadata) {
                if (!in_array($metadata->getName(), $this->ignoredEntities)) {
                    $newMetadata[] = $metadata;
                }
            }
            return parent::executeSchemaCommand($input, $output, $schemaTool, $newMetadata, $ui);
        }
    }
    

    PS: credits go to Marco Pivetta for putting me on the right track. https://groups.google.com/forum/?fromgroups=#!topic/doctrine-user/rwWXZ7faPsA