加载Symfony2灯具时出错“在非对象上调用成员函数”

时间:2013-05-29 10:15:18

标签: symfony doctrine load fixtures

我正在使用Symfony2实现经典的博客应用程序,而“app / console doctrine:fixtures:load”会返回错误。我的BlogFixtures.php文件是这样的:

<?php
namespace MGF\Bundles\WebBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use MGF\Bundles\WebBundle\Entity\Blog;
use MGF\Bundles\CRMBundle\Util\Util;

class BlogFixtures extends AbstractFixture implements FixtureInterface
{
    public function load(ObjectManager $em)
    {
        $blog1 = new Blog();

        $title = 'First post';
        $blog1->setTitle($title);

        $slug1 = Util::getSlug($title);
        $blog1->setSlug($slug1);

        $blog1->setImage('beach.jpg');
        $blog1->setTags('symfony2, php, paradise, symblog');
        $blog1->setCreated(new \DateTime('now'));
        $blog1->setUpdated($blog1->getCreated());

        $em->persist($blog1);

        $author1 = $em->getRepository('MGFBCBundle:User')->findOneByUser('sarah');
        $author1->addBlog($blog1);

        $em->persist($author1);
        $em->flush();
    }
}

错误:

app/console doctrine:fixtures:load
Careful, database will be purged. Do you want to continue Y/N ?Y
  > purging database
  > loading MGF\Bundles\WebBundle\DataFixtures\ORM\BlogFixtures
PHP Fatal error:  Call to a member function addBlog() on a non-object in /var/www/METRO/src/MGF/Bundles/WebBundle/DataFixtures/ORM/BlogFixtures.php on line 33

Fatal error: Call to a member function addBlog() on a non-object in /var/www/METRO/src/MGF/Bundles/WebBundle/DataFixtures/ORM/BlogFixtures.php on line 33

我不知道哪里出错了。任何提示?

提前致谢。

1 个答案:

答案 0 :(得分:1)

问题在于,即使用户'sarah'存在于数据库的数据库中,当尝试再次加载数据时,db也会被清除。所以我需要在从灯具创建时引用我的用户,并通过他们的参考检索它们,如下所述:

http://symfony.com/doc/master/bundles/DoctrineFixturesBundle/index.html#sharing-objects-between-fixtures

灯具装载再次正常工作。