我用一个理论Article
实体的例子简化了我的问题。
我的文章有标题,内容类别和类型
我的灯具在分开的YAML文件中写入
# category.yml
AppBundle\Entity\Category:
category_1:
id: 1
name: foo
category_2:
id: 2
name: bar
# type.yml
AppBundle\Entity\Type:
type_1:
id: 1
name: baz
type_2:
id: 2
name: qux
# article.yml
AppBundle\Entity\Article:
article_1:
id: 1
title: "Lorem ipsum dolor sit amet, consectetur"
content: "Lorem ipsum dolor sit amet, consectetur"
category: '@category_1'
问题是我在Events::preUpdate
上有一个DoctrineListener,它更新Article :: type取决于Article :: Category
/**
* Doctrine Listener
*/
class ArticleListener
{
// ...
private function preUpdate(LifecycleEventArgs $args)
{
$article = $args->getEntity();
// Get type from DB
$type = $em->getRepository('AppBundle:Type')->find(1)
$article->setType($type);
}
}
所以载入类别&首先输入夹具
class BasicFixtures extends Fixture
{
public function load(ObjectManager $manager)
{
$files = [
'category' => __DIR__.'/../../../AppBundle/DataFixtures/category.yml',
'type' => __DIR__.'/../../../AppBundle/DataFixtures/type.yml',
//... other yml files
];
$loader = new NativeLoader();
$objectSet = $loader->loadFiles($files);
foreach ($objectSet->getObjects() as $key => $object) {
$this->addReference($key, $object);
$manager->persist($object);
}
$manager->flush();
}
}
然后我用DependentFixtureInterface::getDependencies
加载我的文章夹具,以确保已加载类别和类型
class ArticleFixtures extends Fixture implements DependentFixtureInterface
{
public function load(ObjectManager $manager)
{
// This give me my object
dump($this->getReference('category_1'));
$files = [
'article' => __DIR__.'/../../../AppBundle/DataFixtures/article.yml',
//... other yml files
];
$loader = new NativeLoader();
$objectSet = $loader->loadFiles($files);
foreach ($objectSet->getObjects() as $key => $object) {
$manager->persist($object);
}
$manager->flush();
}
public function getDependencies()
{
return [
BasicFixtures::class,
];
}
}
但是随之而来的是,“@ category_1”的引用将丢失
In FixtureNotFoundExceptionFactory.php line 23:
[Nelmio\Alice\Throwable\Exception\Generator\Resolver\FixtureNotFoundException]
Could not find the fixture "category_1".
我做错了什么? 非常感谢您的帮助
答案 0 :(得分:1)
你必须在BasicFixture中命名你的引用。
// other fixtures can get this object using the 'admin-user' name
$this->addReference('category_1', $userAdmin);
然后在ArticleFixture中使用给定的名称获取该引用。
$object->addCategory($this->getReference('category_1'));
$manager->persist($object);
供参考:
在灯具之间共享对象:
按顺序加载灯具文件: