Load Container and EntityManager within a fixture in Symfony2

北城以北 提交于 2020-01-02 22:02:14

问题


I have two fixtures, one LoadSport.php and one LoadCategory.php in my Symfony project.

Every instance of sport has a private 'category' attribute which is an instance of Category. I am trying to retrieve the categories I already in my database and load them in the Sports fixture (I chose some sports). I followed the official using container within fixtures (http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html#using-the-container-in-the-fixtures) as suggested in another thread.

So this is my code for the LoadSport.php:

class LoadSport implements FixtureInterface, ContainerAwareInterface
{
    private $container;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;  
    }

    public function load(ObjectManager $manager)
    {
        $i = 0;
        $em = $this->container->get('doctrine')->getManager();
        $category = $em->getRepository("MyBundle:Category")->findOneById(1);
        $names = array('SportA', 'SportB', 'SportC');


        foreach($names as $name)
        {
            $sport = new Sport();
            $sport->setName($name);
            $sport->setCategory($category);

            $manager->persist($sport);
        }

        $manager->flush();
    }

    public function getOrder()
    {
        return 2;
    }

I tried to call a separate manager to get Category n1, and when I do php app/console doctrine:fixture:load, I get this error message:

[Symfony\Component\Debug\Exception\ContextErrorException] Catchable Fatal Error: Argument 1 passed to MyBundle\Entity\Sport::setCategory() must be an instance of MyBundle\Entity\Category, null given, called in .../MyBundle/DataFixtures/ORM/LoadSport.php on line xx and defined

How can I retrieve the category of id 1. or any other category within my LoadSport.php fixture and set the category of the Sport instance? What am I doing wrong? Why am I getting a null value wheras as it should be a category entity?

Many thanks in advance.


回答1:


Use the ObjectManager passed into the load function. Like so:

$category = $manager->getRepository('MyBundle:Category')->findOneById(1);

Update:

As pointed out below, whilst this approach is nice and simple it can lead to problems when manipulating data in the fixtures. The Symfony Docs details the correct way to do this.



来源:https://stackoverflow.com/questions/31493548/load-container-and-entitymanager-within-a-fixture-in-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!