如何使用2个外键在Entity内部加载灯具?

时间:2018-12-26 18:15:34

标签: php doctrine symfony4

我有3个实体:许可证,负责任和特殊。 负责人可以管理许多许可证,而Specialite可以拥有许多许可证。 我已经为负责任和特殊创建了固定装置。 但是,我尝试了以下代码以在Licence中加载Fixture,但是它不起作用?有帮助吗?

<?php

namespace App\DataFixtures;

use App\Entity\Licence;
use App\Entity\Responsable;
use App\Entity\Specialite;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;

class LicenceFixtures extends Fixture
{

private $specialites;

private $responsables;

public function __construct(EntityManagerInterface $em)
{
    $this->specialites = $em->getRepository(Specialite::class);

    $this->responsables = $em->getRepository(Responsable::class);

}
public function load(ObjectManager $manager)
{



    for ($i = 0; $i < 5; $i++) {

    $specialite = $this->specialites->find($i+9);

    $resp = $this->responsables->find($i+1);

        $licence = new Licence();
        $licence->setTitre('licence '.$i);
        $licence->setCode('code'.$i);
        $licence->setEtablissement('etabli'.$i);
        $licence->setDateOuverture('2018/2019');
        $licence->setSpecialite($specialite);
        $licence->setResponsable($resp);
        $manager->persist($licence);


    }

    $manager->flush();

}
}

1 个答案:

答案 0 :(得分:0)

您应该指定loading order来解释该学说的正确顺序,这样它将首先加载所有负责任和特殊的人

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

然后,使用AbstractFixture setReferenceaddReference方法正确地share entities

SpecialityFixtures中,您可以这样做:

$speciality = new Speciality();    
$this->addReference('some.name', $speciality);
$this->em->persist($speciality);

LicenceFixtures中:

   $licence->setSpecialite($this->getReference('some.name'));