2

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?

1

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Let's assume I have a serialized string with multiple mentions of field/class in it, which should be removed. What should I do? Write a regexp? It's insane as you understand. So generally you are correct, but in some cases it's required to inject the em and make changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.