2014-10-30 68 views
5

我有很多的实体项目课程,因为每门课程可以有很多项目,很多项目可能与之间的一个关系相同的课程。Symfony2中:警告:spl_object_hash()预计参数1是对象,整数给出

这是我的实体:

class Project{ 

    /** 
    * @ORM\Id 
    * @ORM\Column(type="integer") 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    protected $id; 

    //... other fields ... 


    //----------------------- DATABASE RELATIONSHIP ----------------// 

    //PROJECT-COURSE - M:1 relationship 
    /** 
    * @ORM\ManyToOne(targetEntity="Course", inversedBy="project") 
    * @ORM\JoinColumn(name="course_id", referencedColumnName="id") 
    **/ 
    private $course; 

class Course{ 

    /** 
    * @ORM\Id 
    * @ORM\Column(type="integer") 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 

    //... other fields ... 

    //----------------------- DATABASE RELATIONSHIP----------------// 

    //COURSE-PROJECT 1:M relationship 
    /** 
    * @ORM\OneToMany(targetEntity="Project", mappedBy="course") 
    **/ 
    private $project; 

当我尝试插入一个新的项目我当然会出现错误,这是我的表单生成器:

  $builder 
       ->add('name', 'text', array(
        'attr' => array('class' => 'form-control'))) 
       ->add('description', 'textarea', array(
        'attr' => array('class' => 'form-control', 'rows' => '10'))) 
       ->add('submit', 'submit', array(
        'attr' => array('class' => 'btn btn-primary'))); 

我尝试插入这些数据创建一个Project对象,并填写表单的结果,你可以见:

$project->setName($form->get('name')->getData()); 
       $project->setDescription($form->get('description')->getData()); 
       $project->setPhasesNumber($form->get('phases_number')->getData()); 
       $project->setPathNumber($form->get('path_number')->getData()); 
       $project->setYear(date('Y')); 
       $project->setCourse(5); //number 5 is just a test 

       $em = $this->getDoctrine()->getManager(); 
       $em->persist($project); 
       $em->flush(); 

的问题应该与命令$project->setCourse(5);,我已经看到了,如果我删除项目和课程之间的关系的错误不会出现。即使我评论用于设置课程ID的行,该错误也会消失,所以我认为我与这种关系有问题,但我无法理解在哪里。

我刚刚在stackoverflow上阅读了这样的其他问题,但它并没有帮助我。

在此先感谢。

回答

6

它正在寻找使用带有Course实例的实例的对象,但仅传递该课程的ID不起作用。

你可以这样做:

//... 
$course = $this->getDoctrine() 
       ->getManager() 
       ->getRepository('Namespace:Course') 
       ->findOneById(5); 
$project->setCourse($course); 
//... 

全方位提到,如果你知道该实体已经存在,你可以只通过执行设置没有DB查询:

$project->setCourse($this->getDoctrine() 
         ->getManager() 
         ->getReference('Namespace:Course', 5) 
); 
+0

现在更清晰,谢谢,真的;) – 2014-10-30 23:54:46

+0

花了我几个小时来达到这一点,你的解决方案真的很有帮助。谢谢 – 2015-08-14 10:10:24

+1

其实最好是使用 '$ this-> getDoctrine() - > getManager() - > getReference('Namespace:Course',5);' 不需要在db中搜索! – Full 2016-07-13 07:58:06

相关问题