How can i store a default record using the migration file?
In symfony/doctrine there are a method like postUp()
which is missing in shopware
.
So how can i do this? The shopware doc provides a tutorial Creating data with a given ID, but i cannot initialize the needed repository.
So how can i access the entityRepository inside the migration class? Or is there another way to create a default record?
The recommended way is to just create the table in the migration file and then upsert the default records in the activate
and update
methods of the Plugin class. See answer by @dneustadt
Please read the comments to this answer for further information.
You can't use an EntityRepository inside a migration file. You can only use raw SQL queries by using the $connection
variable which is passed to the update
method.
Example:
<?php declare(strict_types=1);
namespace Swag\BasicExample\Migration;
use Doctrine\DBAL\Connection;
use Shopware\Core\Framework\Migration\MigrationStep;
use Shopware\Core\Framework\Uuid\Uuid;
class Migration1611740369ExampleDescription extends MigrationStep
{
public function getCreationTimestamp(): int
{
return 1611740369;
}
public function update(Connection $connection): void
{
// create table
$createTableSql = <<<SQL
CREATE TABLE IF NOT EXISTS `swag_basic_example_general_settings` (
`id` INT NOT NULL,
`example_setting` VARCHAR(255) NOT NULL,
`created_at` DATETIME(3) NOT NULL,
`updated_at` DATETIME(3),
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
SQL;
$connection->executeStatement($createTableSql);
// insert default setting
$insertDefaultSettingSql = <<<SQL
INSERT INTO `swag_basic_example_general_settings`
(`id`, `example_setting`, `created_at`)
VALUES (:id, :example_setting, NOW())
SQL;
$connection->executeStatement(
$insertDefaultSettingSql,
[
'id' => Uuid::randomBytes(),
'example_setting' => 'example_value',
]
);
}
public function updateDestructive(Connection $connection): void
{
}
}
Note: When using Connection
instead of an entity repository you need to use Uuid::randomBytes()
instead of Uuid::randomHex()
. If you want to use an existing ID instead of a generated one you can use Uuid::fromHexToBytes('0fa91ce3e96a4bc2be4bd9ce752c3425')