ultimatum
ultimatum

Reputation: 417

Symfony5 fixtures with order - getOrder() doesn't work

When I added new fixtures file

/**
 * {@inheritdoc}
 */
public function load(ObjectManager $manager): void
{
    // get user fixtures
    $user = $this->getReference(LoadUserData::USER_REFERENCE);
    $userSecond = $this->getReference(LoadUserData::USER_TWO_REFERENCE);

    $productFirst = Product::create($user, 'title1', 'title1', 'description3', null, null);
    $manager->persist($productFirst);

    $productSecond = Product::create($user, 'title2', 'title2', 'description2', null, null);
    $manager->persist($productSecond);

    $productThird = Product::create($userSecond, 'title3', 'title3', 'description3', null, null);
    $manager->persist($productThird);

    $manager->flush();
}

/**
 * @return array
 */
public static function getGroups(): array
{
    return ['demo', 'default'];
}

I caught error

purging database

loading DataFixtures\LoadUserData

In ReferenceRepository.php line 154:

Reference to "ROLE_USER" does not exist

Class LoadRoleData has method getOrder(), but it doesn't work.

public function getOrder()
{
    return 1; // the order in which fixtures will be loaded
}

Earlier all were done.

purging database

loading DataFixtures\LoadRoleData

loading DataFixtures\LoadUserData

...

UPDATE: Class LoadUserData has

    /**
     * {@inheritdoc}
     */
     public function getDependencies()
     {
        return [
            LoadRoleData::class
        ];
     }

But it doesn't work too ((

How can I set order for Role Fixtures in Symfony5?

Upvotes: 2

Views: 1135

Answers (1)

mpaden
mpaden

Reputation: 171

Instead of you deciding on the order of inserting fixtures, you should let Symfony decide.

To do that, your fixture classes should implement DependentFixtureInterface and override method getDependencies(). In your case, it should look like this:

<?php

namespace App\DataFixtures;

class LoadUserData extends Fixture implements DependentFixtureInterface
{

    public function getDependencies()
    {
        return [
            LoadRoleData::class,
        ];
    }

}

Now, Symfony will know that it needs to insert LoadRoleData first.

Using DependentFixtureInterface, you should never worry about the order of inserting if you have set up dependencies correctly.

Upvotes: 9

Related Questions