简体   繁体   中英

Fixture DOCTRINE2

When I use:

php app/console doctrine:fixtures:load --fixtures=/var/www/Symfony/src/BISSAP/ForumBundle/DataFixtures/ORM**

I get the following error:

PHP Catchable fatal error: Argument 1 passed to BISSAP\\ForumBundle\\Entity\\Forum::setCategory() must be an instance of BISSAP\\ForumBundle\\Entity\\Category, null given, called in /var/www/Symfony/src/BISSAP/ForumBundle/DataFixtures/ORM/LoadForum.php on line 40 and defined in /var/www/Symfony/src/BISSAP/ForumBundle/Entity/Forum.php on line 184

My Fixture - LoadForum.php:

<?php
namespace BISSAP\ForumBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use BISSAP\ForumBundle\Entity\Forum;
use BISSAP\ForumBundle\Entity\Category;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class LoadForum extends Controller implements FixtureInterface
{

 public function load(ObjectManager $manager)
 {
    $data=array(array('NAME','DESCRTIPTION','60',$manager->getRepository('BISSAPForumBundle:Category')->find('1')),
                array('NAME2','DESCRTIPTION2','60',$manager->getRepository('BISSAPForumBundle:Category')->find('2')));

    foreach ($data as $for) {
      $forum = new Forum();
      $forum->setName($for[0]);
      $forum->setDescription($for[1]);
      $forum->setOrdre($for[2]);
      $forum->setCategory($for[3]);

      $manager->persist($forum);
      }

    $manager->flush();
  }
}

doctrine:fixtures:load erases all data from DB and loads new set of fixtures

I believe your problem is

$manager->getRepository('BISSAPForumBundle:Category')->find('1')

that return empty result instead of Category object

And it looks like either you loads Forum fixtures before Category or you didn't considered that DB was erased and you don't have any records for Category.

for case 1 you should change order of fixtures loading - change the function "getOrder" for Category fixtures and set returned number lower then number at Forum

for case 2 you should also create fixtures for some categories

BTW you should use a reference to the object, instead of picking up from the repository, so common way is:

  1. Create new reference for the Category fixture

    $category = new \\MyApp\\CategoryBundle\\Entity\\Category();

    $category->setName();

    $this->addReference('MyApp\\CategoryBundle\\Entity\\Category-1',$category);

  2. Call created reference to fill Forum

    $forum->setCategory($this->getReference('MyApp\\CategoryBundle\\Entity\\Category-1'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM