How to insert multiple rows from a data array in a Doctrine migration?

2.6k views Asked by At

I have created an Entity and generated the migration file. Now, I want to insert some data into the table in the MySQL database when doing the migration.

My up function is as follows.

public function up(Schema $schema) : void
{
  $data = array(
    'My Data 1',
    'My Data 2',
    'My Data 3',
  );

  $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

  $this->addSql('CREATE TABLE my_table (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(100) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');

  $this->addSql('INSERT INTO my_table (name) VALUES (?)', $data, \PDO::PARAM_STR);
}

I want to add all data in the $data array to my_data table. All elements in the $data array are strings.

When I run php bin/console doctrine:migrations:migrate, it gives the following error.

Argument 3 passed to Doctrine\Migrations\AbstractMigration::addSql() must be of the type array, int given...

How to fix this error and achieve what I want?

2

There are 2 answers

0
Sennen Randika On BEST ANSWER

I managed to achieve what I wanted as follows... This answer is inspired by the resources commented on my question by @El_Vanja.

public function up(Schema $schema) : void
{
  $data = array(
    'My Data 1',
    'My Data 2',
    'My Data 3',
  );

  $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

  $this->addSql('CREATE TABLE my_table (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(100) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');

  foreach($data as $d) {
    $this->addSql('INSERT INTO my_table (name) VALUES (?)', array($d));
  }
}
1
Michel Rummens On

Very late to the party, but perhaps this will help someone in the future. Using an associative array as input for the query described in Sennen Randika' answer will not work and throws the following error: Positional parameter at index 0 does not have a bound value.

So do not use an array structure as below:

  $data = array(
    'key1' => 'My Data 1',
    'key2' => 'My Data 2',
    'key3' => 'My Data 3',
  );