如何使用迁移文件存储默认记录?
在符号/学说中,有一种类似postUp()
的方法,而shopware
中缺少这种方法。那么我该怎么做呢?shopware文档提供了一个使用给定ID创建数据的教程,但我无法初始化所需的存储库。
那么如何访问迁移类内部的entityRepository?或者有其他方法可以创建默认记录吗?
建议的方法是只在迁移文件中创建表,然后在Plugin类的activate
和update
方法中追加默认记录。查看@dneustadt的回答
请阅读对此答案的评论以了解更多信息
不能在迁移文件中使用EntityRepository。只能通过使用传递给update
方法的$connection
变量来使用原始SQL查询。
示例:
<?php declare(strict_types=1);
namespace SwagBasicExampleMigration;
use DoctrineDBALConnection;
use ShopwareCoreFrameworkMigrationMigrationStep;
use ShopwareCoreFrameworkUuidUuid;
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
{
}
}
注意:当使用Connection
而不是实体存储库时,需要使用Uuid::randomBytes()
而不是Uuid::randomHex()
。如果你想使用现有的ID而不是生成的ID,你可以使用Uuid::fromHexToBytes('0fa91ce3e96a4bc2be4bd9ce752c3425')
在Plugin
扩展中,您可以访问DI容器并获得任何公共服务,包括存储库:
class MyPlugin extends Plugin
{
public function activate(ActivateContext $context)
{
$productRepository = $this->container->get('product.repository');
}
}