Recently I came accross a problem with entity that was mapped to view in database. In such scenario calling doctrine:schema:update
command was producing errors.
I know that we can create custom schema based command tool but I think that my solution is easier and more efficient. The solution is using Doctrine2
: postGenerateSchema
event listener – to remove entity or table (depending on context) from Schema
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
namespace AppBundle\EventListener; use Doctrine\ORM\Tools\Event\GenerateSchemaEventArgs; use Doctrine\ORM\EntityMAnagerInterface; /** * IgnoreTablesListener class */ class IgnoreTablesListener { private $ignoredTables = [ 'table_name_to_ignore', ]; // or depending on context and what you need private $ignoredEntities = [ 'AppBundle:IgnoredEntity', ]; /** * Remove ignored tables /entities from Schema * * @param GenerateSchemaEventArgs $args */ public function postGenerateSchema(GenerateSchemaEventArgs $args) { $schema = $args->getSchema(); $em = $args->getEntityManager(); $ignoredTables = $this->ignoredTables; // or prepare $ignoredTables array $ignoredTables = []; foreach ($this->ignoredEntities as $entityName) { $ignoredTables[] = $em->getClassMetadata($entityName)->getTableName(); } foreach ($schema->getTableNames() as $tableName) { if (in_array($tableName, $ignoredTables)) { // remove table from schema $schema->dropTable($tableName); } } } } |
And register listener:
1 2 3 4 5 |
ignore_tables_listener (with dependencies if needed): class: AppBundle\EventListener\IgnoreTablesListener # add constructor dependency if needed tags: - {name: doctrine.event_listener, event: postGenerateSchema } |
I have presented both versions: when we want to ignore tables and entities – you should select the most appropriate for you.
Note that Schema
instance is created (generated) – not executed. In this case calling dropTable
method means unset table from Schema
instance. If you call:
1 |
app/console d:s:u --dump-sql |
you will receive generated schema SQL without tables you want to ignore.
Pingback: How to disable FOREIGN KEY CONSTRAINT when using Doctrine generate migration? – News BruinsExtra()
Pingback: How to set up entity (doctrine) for database view in Symfony 2()
Pingback: How to set up entity (doctrine) for database view in Symfony 2 - Code Solution()