在固定装置 class 中检索用户

Retrieve user in fixtures class

我必须测试我的应用程序,所以我想使用 doctrine 的固定装置将数据插入数据库。我想创建一个与用户实体 (fosuser) 具有 ManyToOne 关系的实体(例如博客 post)的新条目。因此,我必须检索第一个用户以设置为博客 post 作者。问题是当我 运行 命令时:

php app/console doctrine:fixtures:load

我收到以下错误:

Catchable fatal error: Argument 1 passed to BluEstuary\PostBundle\Model\Post::setOwner() 
must be an instance of BluEstuary\UserBundle\Model\User, null given, called in /Users/bface007/workspace/BluEstuary/esgis_gabon/src/ESGISGabon/PostBundle/DataFixtures/ORM/Posts.php on line 53 and defined in /Users/bface007/workspace/BluEstuary/esgis_gabon/src/BluEstuary/PostBundle/Model/Post.php on line 296`

我可以在非 fixtures classes 中检索用户,但是当我在 fixtures 中尝试时它总是给出空值。有人可以帮助我吗?

这是我的灯具class:

class Posts implements FixtureInterface, ContainerAwareInterface{
    public function load(Objectmanager $manager){
        $blogposts = array(
            array(
                "title" => "This is test 1",
                "content" => "I am a cool example"
            ),
            array(
                "title" => "This is test 2",
                "content" => "I am a cool example"
            )
        );

        $userManager = $this->container->get('fos_user.user_manager');
        $user = $userManager->findUserBy(array("id" => 3));

        foreach($posts as $i => $post){
            $new_posts[$i] = new BlogPost();
            $new_posts[$i]->setPostTitle($post["title"])
                        ->setPostContent($post["content"]);

            $new_posts[$i]->setAuthor($user);

            $manager->persist($new_posts[$i]);
        }

        $manager->flush();
    }
}

您想使用:

php app/console doctrine:fixtures:load --append

...所以它不会事先清空您的数据库

(来源:https://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html

将正确的数据加载到夹具中的正确方法是使用引用。 假设您有一个 Author 装置:

AuthorFixture extends AbstractFixture implements OrderedFixtureInterface {
public function load(ObjectManager $om)
{
   $author = new Author("name", "surname"..);
   $this->setReference("author_1", $author);

   $om->persist($author);
   $om->flush();
}

/**
 * Get the order of this fixture
 * NOTE: the author comes before the Posts
 * @return integer
 */
public function getOrder()
{
    return 1;
}

}

然后在您的 post 夹具中:

new_posts[$i] = new BlogPost();
new_posts[$i]->setAuthor($this->getReference("author_1");

..

/**
 * Get the order of this fixture
 * Note: the post comes after the author
 * @return integer
 */
public function getOrder()
{
    return 2;
}