2015-09-25 33 views
0

我必須測試我的應用程序,所以我想使用教義的燈具在數據庫中插入數據。我想創建一個與用戶實體(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(); 
    } 
} 
+0

,必須先創建用戶,因爲空數據庫。 – malcolm

+0

你是對的。我沒有想到這一點。 – bface007

回答

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

Yessss!這絕對是正確的方式。謝謝erlangb – bface007

+0

不客氣! – erlangb