【问题标题】:Retrieve user in fixtures class在夹具类中检索用户
【发布时间】:2015-09-25 14:35:05
【问题描述】:

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

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`

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

这是我的灯具类:

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

【问题讨论】:

  • 你应该先创建用户,因为数据库是空的。
  • 你说的太对了。我没想到。

标签: symfony doctrine-orm fosuserbundle fixtures


【解决方案1】:

你想使用:

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

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

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

【讨论】:

  • 马尔科姆,你说得对。我没想到。
  • 这帮助我理解了为什么 $repository->find(1) 不起作用。谢谢
【解决方案2】:

将正确的数据加载到夹具中的正确方法是使用引用。 假设您有一个 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;
}

}

然后在你的后期夹具中:

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

【讨论】:

  • 是的!这绝对是正确的方法。谢谢erlangb
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 2012-05-04
相关资源
最近更新 更多