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{ /** * @ORMId * @ORMColumn(type="integer") * @ORMGeneratedValue(strategy="AUTO") */ protected $id; //... other fields ... //----------------------- DATABASE RELATIONSHIP ----------------// //PROJECT-COURSE - M:1 relationship /** * @ORMManyToOne(targetEntity="Course", inversedBy="project") * @ORMJoinColumn(name="course_id", referencedColumnName="id") **/ private $course;
and
class Course{ /** * @ORMId * @ORMColumn(type="integer") * @ORMGeneratedValue(strategy="AUTO") */ //... other fields ... //----------------------- DATABASE RELATIONSHIP----------------// //COURSE-PROJECT 1:M relationship /** * @ORMOneToMany(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 try to insert these data creating a Project object and filling it with the result of the form 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’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.
Advertisement
Answer
It’s 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() ->getManager() ->getRepository('Namespace:Course') ->findOneById(5); $project->setCourse($course); //...
As @Full mentions if you know that the entity already exists you can just set it without a DB lookup by doing:
$project->setCourse($this->getDoctrine() ->getManager() ->getReference('Namespace:Course', 5) );