Home Blog Contact

How to create a migration in Shopware 6?

Jan 27th 2022

Migrations are PHP files that enable plugin changes from version to version. Most of the changes are related to the database such as create table, remove columns, update data and etc. This is a short tutorial, but if you are looking for a more detailed content, please visit the official documentation.

php bin/console database:create-migration -p MatheusGontijoHelloWorld --name CreateBookTable

Result:

Creating migration...
Creating plugin-migration with namespace MatheusGontijo\HelloWorld\Migration in path custom/plugins/MatheusGontijoHelloWorld/src/Migration...
Creating core-migration ...
Migration created: "custom/plugins/MatheusGontijoHelloWorld/src/Migration/Migration1642871281CreateBookTable.php"

You can noticed that the migration file has been created in the Migration directory. The file naming is Migration (prefix) + 1642871281 (timestamp) + BookExample (just a short description about the migration purpose).

Please, go to the Migration directory and edit the created file. Make sure you add your logic into the update method, like the following:

<?php declare(strict_types=1);

namespace MatheusGontijo\HelloWorld\Migration;

use Doctrine\DBAL\Connection;
use Shopware\Core\Framework\Migration\MigrationStep;

class Migration1642871281CreateBookTable extends MigrationStep
{
    public function getCreationTimestamp(): int
    {
        return 1642871281;
    }

    public function update(Connection $connection): void
    {
        $query = <<<SQL
        CREATE TABLE IF NOT EXISTS `matheusgontijo_book` (
          `id` binary(16) NOT NULL,
          `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
        SQL;

        $connection->executeStatement($query);
    }

    public function updateDestructive(Connection $connection): void
    {
    }
}

Run the following command to execute the migration:

php bin/console database:migrate MatheusGontijoHelloWorld --all

Result:

Get collection for identifier: "MatheusGontijoHelloWorld"
migrate Migrations
 1/1 [============================] 100%

 ---------- ----------------------
  Action     Number of migrations
 ---------- ----------------------
  Migrated   1 out of 1
 ---------- ----------------------

all migrations for identifier: "MatheusGontijoHelloWorld" executed
cleared the shopware cache

Done! I checked the database and the new table matheusgontijo_book has been created.

Information to keep in mind


Hope that helped you! See you on the next blogpost!