Symfony2: Warning: spl_object_hash() expects parameter 1 to be object, integer given

不羁岁月 提交于 2019-12-05 00:20:58


I have a many to one relationship between the entities Project and Course because each course can have many projects so many projects could be related to the same course.

These are my entities:

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;

The error appears when i try to insert a new project for my course, this is my form 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')));

I try to insert these data creating a Project object and filling it with the result of the form as you can see:

                $project->setCourse(5); //number 5 is just a test

                $em = $this->getDoctrine()->getManager();

The problem should be related to the command $project->setCourse(5); and I've seen that if i remove the relationship between Project and Course the bug doesn't appear. The bug disappears even if I comment the line used to set the course id, so I think I have a problem with this relationship but I can't understand where.

I've just read other question like this on stackoverflow but it doesn't help me.

Thanks in advance.


Its looking for you to use an object with an instance of Course just passing the ID of the course does not work.

You could do:

$course = $this->getDoctrine()

As Full mentions if you know that the entity already exists you can just set it without a db lookup by doing:

                         ->getReference('Namespace:Course', 5)