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

I have many relationships between Project and Course objects, because each course can have many projects, so many projects can be associated with 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; 

and

 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:

  $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 am trying to insert this data by creating a Project object and filling it with the form result, as you can see:

 $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(); 

The problem should be related to the command $project->setCourse(5); , and I saw that if I delete the relationship between Project and Course, the error will not appear. The error disappears even if I comment on the line used to set the course identifier, so I think I have a problem with these relationships, but I cannot figure out where.

I just read other questions like this one on stackoverflow, but that doesn't help me.

Thanks in advance.

+5
source share
1 answer

It is looking for you to use an object with an instance of Course , just passing the identifier of the course does not work.

You can do:

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

As stated in Full, if you know that the object already exists, you can simply install it without searching for db by doing:

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

Source: https://habr.com/ru/post/1205907/


All Articles