我必须测试我的应用程序,所以我想使用doctrine的fixture来在数据库中插入数据。我想创建一个实体的新条目(例如博客文章),它与用户实体(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`
我可以在非fixtures类中检索用户,但是当我尝试使用fixtures时它总是给出null值。有人可以帮帮我吗?
这是我的灯具类:
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();
}
}
答案 0 :(得分:0)
您想使用:
php app/console doctrine:fixtures:load --append
...所以它不会事先清空你的数据库
(资料来源:https://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html)
答案 1 :(得分:0)
将正确的数据加载到夹具中的正确方法是使用参考。 假设您有一个作者夹具:
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;
}