Home > Software design >  Symfony / Fixtures "Reference already exists, use method setReference in order to override it&q
Symfony / Fixtures "Reference already exists, use method setReference in order to override it&q

Time:11-12

I created 2 fixtures files and want to link them but got the error : Reference to "genre_reference" already exists, use method setReference in order to override it.

Here is my book fixtures :

class LivreFixtures extends Fixture implements DependentFixtureInterface
{
    public function load(ObjectManager $manager): void
    {
        $faker = Factory::create('fr_FR');
        $faker->seed(123);

        for ($i = 0; $i < 10; $i  ) {
            $livre = new Livre();
            $livre->setTitre($faker->sentence($nbWords = 4, $variableNbWords = true));
            $livre->setAuteur($faker->name);
            $livre->setDescription($faker->text);
            $livre->setDateDeParution($faker->dateTime($format = 'Y-m-d'));
            $livre->setGenre($this->getReference('genre_reference'));
            $manager->persist($livre);
        }

        $manager->flush();
    }

    public function getDependencies()
    {
        return array(
            GenreFixtures::class,
        );
    }
}

And my genre fixtures file :

class GenreFixtures extends Fixture
{

    public function load(ObjectManager $manager): void
    {
        $faker = Factory::create('fr_FR');
        $faker->seed(123);
        
        for ($i=0; $i < 5; $i  ) {
          $genre = new Genre();
          $genre->setName($faker->colorName);
          $manager->persist($genre);
          $this->addReference('genre_reference', $genre);
        }

      $manager->flush();
    }
}

I don't really understand the setreference method, how to do it. Any help ?

CodePudding user response:

I think you should add $i to your genre reference name.

$this->addReference('genre_reference_' . $i, $genre);

After that, you can use it by

$this->getReference('genre_reference_0');
//OR
$this->getReference('genre_reference_1');
//OR
$this->getReference('genre_reference_' . $i);
  • Related