duanjiu1003 2018-01-24 13:50
浏览 27

Alice Fixture:对实体的引用已经持久化和刷新

I simplified my problem with an exemple of a theoretical Article entity. My Article has a title, content category and a type

My fixtures are writed in separates YAML files

# 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'

The problem is I have a DoctrineListener on Events::preUpdate which update Article::type depends of 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);
    }
}

So load category & type fixtures first

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();
    }
}

And then I load my Article fixture with DependentFixtureInterface::getDependencies to be sure categories and types are already loaded

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,
        ];
    }
}

But it seams with that, the reference of "@category_1" is lost

In FixtureNotFoundExceptionFactory.php line 23:

  [Nelmio\Alice\Throwable\Exception\Generator\Resolver\FixtureNotFoundException]  
  Could not find the fixture "category_1".

What did I do wrong? Many thanks for help

  • 写回答

1条回答

报告相同问题?