Symfony中addReference方法不生效提示writer引用不存在
Symfony数据夹具addReference不生效的原因与解决方法
核心原因
- 夹具加载顺序未做显式约束:Doctrine Fixtures默认不会自动识别夹具间的依赖关系,加载顺序是随机的。如果BookFixtures在WriterFixtures之前执行,调用
getReference()时对应的Writer实例引用还没被注册到引用仓库,就会抛出「Reference to "writer" does not exist」的错误。 - WriterFixtures代码顺序错误:给出的代码里把
$manager->flush()放在了实例化Writer、persist、添加引用的逻辑之前,虽然这行提前执行的flush本身不会直接导致引用丢失,但如果后续逻辑因为提前flush触发异常中断,会直接导致引用注册失败。 - 常量值不匹配:如果
WriterFixtures::WRITER_REFERENCE常量的实际值和传入getReference()的标识字符串不一致,也会触发找不到引用的报错。
修复步骤
- 调整WriterFixtures的代码顺序,把flush操作移到所有persist、addReference逻辑之后,正确代码示例:
public function load(ObjectManager $manager) { $writer = new Writer(); $writer->setName("Kasza Sandor"); $manager->persist($writer); // 先注册引用,最后统一提交 $this->addReference(self::WRITER_REFERENCE, $writer); $manager->flush(); }
- 给BookFixtures显式声明依赖,强制框架先加载WriterFixtures:
首先让BookFixtures实现DependentFixtureInterface接口,然后实现getDependencies()方法返回依赖的夹具类,代码示例:
use Doctrine\Common\DataFixtures\DependentFixtureInterface; use App\DataFixtures\WriterFixtures; class BookFixtures extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $manager) { $book2 = new Book(); $book2->setTitle("Sapiens"); $book2->setReleaseYear(2018); $book2->setDescription("Ez egy elgondolkodtató könyv"); $book2->setImagePath("https://images-na.ssl-images-amazon.com/images/I/41NGcHIqqbL._SX375_BO1,204,203,200_.jpg"); // 此时Writer引用已提前注册,可以正常获取 $book2->addWriter($this->getReference(WriterFixtures::WRITER_REFERENCE)); $manager->persist($book2); $manager->flush(); } // 声明依赖,框架会保证依赖的夹具先加载 public function getDependencies() { return [ WriterFixtures::class, ]; } }
- 校验常量值:确认
WriterFixtures::WRITER_REFERENCE的常量值和引用标识完全匹配,避免拼写错误。
内容的提问来源于stack exchange,提问作者Kasza Sándor
相关产品推荐
相关产品推荐

