0

There is Entities User and Company. Company has user_id.

Now table structure changes and next one user can represent many companies and vice versa (Many to Many eg One to Many - Many to One). This introduces CompanyRepresentative Entity in the middle with fields user_id, company_id and role. Companies user_id will be dropped with that change.

How to make data migration script for that situation? There must be CompanyRepresentative entry for each company present right now that connects same user and company that are connected right now.

Environment is symfony 4 application with Doctrine and Mysql.

Margus Pala
  • 8,433
  • 8
  • 42
  • 52

2 Answers2

5

Doctrine migrations have functions preUp and postUp. In preUp it is possible to select all needed data and in postUp this data can be inserted to correct places after database structure changes.

For example

public function preUp(Schema $schema)
{
    parent::preUp($schema);
    $query = "SELECT id, user_id FROM company";
    $data  = $this->connection->prepare($query);
    $data->execute();
    foreach ($data as $row) {
        $userId         = $row['id'];
        $companyId         = $row['user_id'];
        $this->customSQL[] = "($userId, $companyId)";
    }
}

public function up(Schema $schema)
{
    //Change the schema
}

public function postUp(Schema $schema)
{
    parent::postUp($schema);

    $SQL = 'INSERT INTO company_rep (user_id, company_id) VALUES ' . implode(', ', $this->customSQL);

    $this->connection->executeQuery($SQL);
}
Margus Pala
  • 8,433
  • 8
  • 42
  • 52
-1

You have to use DoctrineMigrationBundle to do this. look at the documentation here, you should get away with it.

Benoît
  • 308
  • 1
  • 10
  • This is already used for changing database tables and schema. Problem is changing the data. – Margus Pala Mar 07 '18 at 16:09
  • There is an exemple [here](https://stackoverflow.com/questions/30411995/doctrine2-how-to-convert-a-one-to-many-to-a-many-to-many-without-losing-data) – Benoît Mar 07 '18 at 16:16