phpmysqlpdodoctrinedoctrine-migrations

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


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?


Solution

  • 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));
      }
    }