简体   繁体   中英

Symfony 4 / doctrine insert initial database data

I am using symfony 4.2 and looking for a way to insert initial data to the database. What I was trying to create is something like an initial setup script that do some sql inserts (like fixtures but for the production environment as well) that can be called by a console command.

I was thinking of using the postUp function in the doctrine migration class but I don't want to rewrite this function for every production environment I set up. Is there a way to use doctrines migration functionality for this purpose or is there a preferred way?

Example workflow:

  • Install symfony by cloning the git repository
  • Execute migrations to create / update the database tables
  • Execute the setup script to insert the needed default values into the database tables

Using the doctrine fixtures bundle in production

While this is discouraged because you can accidentally drop your production database with this, I do see some valid use cases for using the dotrine fixtures bundle in a production environment.

You can edit your config/bundles.php to enable the doctrine fixtures bundle in the production environment.

Change

Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],

to

Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['all' => true],

Create your own command for fixture loading

Using doctrine functionality to manually load the fixtures is also discouraged, but that way you can add additional checks, for example only populate a fresh database.

$fixtures = (new \Doctrine\Common\DataFixtures\Loader())->loadFromDirectory(__DIR__ . '/../src/DataFixture');
$loader = new \Doctrine\Bundle\FixturesBundle\Loader\SymfonyFixturesLoader(new \Symfony\Component\DependencyInjection\Container());
$loader->addFixtures(
    array_map(
        function ($fixture) {
            return [
              'fixture' => $fixture,
              'groups' => []
            ];
        },
        $fixtures
    )
);

$purger = new Doctrine\Common\DataFixtures\Purger\ORMPurger($entityManager);

$executor = new Doctrine\Common\DataFixtures\Executor\ORMExecutor($entityManager, $purger);
$executor->execute(
    $loader->getFixtures()
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM