Search code examples
phpsymfonydoctrinemigrationentitymanager

Access Entity Manager inside Symfony 5 migration class?


I have added a news relation inside my table, and inside the postUp() method I want update all my Threads.

How can I access to the EntityManager inside my migration class for get all my thread, update them and persist/flush my modifications please?


Solution

  • Doctrine migration tool is aimed to execute SQL queries for you in order to amend your database schema. It has nothing to do with your persistent objects, as it operates on a database level, instead of an ORM level. You can write SQL queries to update related database records. Also, you can use a database connection within a migration script in order to fetch data you need from a database. Here is a simple example to give you a starting point.

    foreach ($this->connection->fetchAll('SELECT id FROM table') as $id) {
        $ids = $this->connection->fetchAll(
            'SELECT some_id FROM another_table WHERE whatever_id = :whateverId GROUP BY some_id',
            [
                'whateverId' => $id['id']
            ]
        );
    
        $this->addSql(
            'UPDATE table_to_update SET some_field = :someField WHERE id = :some_id',
            [
                'someField' => implode(
                    ',',
                    array_map(
                        static function (array $data) {
                            return $data['some_id'];
                        },
                        $ids
                    )
                ),
                'some_id' => $id['id']
            ]
        );
    }
    

    As an alternative for the case if you absolutely cannot solve your problem without accessing your persistent objects (for instance if you need to apply some business logic within a migration or a migration logic is beyond a simple schema change), it's better to write a Symfony Console Command and inject EntityManager, repositories and whatever you may need. This console command would be executed one time to apply a complex migration and then decommissioned within a next release.