Reputation: 856
I have 2 entities
and they are setup in oneToOne bidirectional
User.orm.yml
oneToOne:
jobSeekerProfile:
targetEntity: AppBundle\Entity\JobSeekerProfile
mappedBy: jobSeekerUser
cascade: ["persist"]
JobSeekerProfile.orm.yml
oneToOne:
jobSeekerUser:
targetEntity: AppBundle\Entity\User
inversedBy: jobSeekerProfile
Scenario 1
Now inside my controller I am trying to save my inverse side of the relationship, the data gets saved but not the relationship ID.
if ($form->isValid()) {
$user = $form->getData();
// encode the password manually
$encodedPassword = $this->get('security.password_encoder')->encodePassword($user, $form->get('plainPassword')->getData());
$user->setPassword($encodedPassword);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->get('session')->getFlashBag()->add(
'success',
$this->get('translator')->trans('success_registration')
);
return $this->redirect($this->generateUrl('login'));
}
Scenario 2
If I change my controller to as following the relationship id gets saved. but then 2 records are added to the table one with relationship id and one without.
if ($form->isValid()) {
$user = $form->getData();
// encode the password manually
$encodedPassword = $this->get('security.password_encoder')->encodePassword($user, $form->get('plainPassword')->getData());
$user->setPassword($encodedPassword);
$em = $this->getDoctrine()->getManager();
$JS = new JobSeekerProfile();
$JS->setFirstName($form->get('jobSeekerProfile')['firstName']->getData());
$JS->setLastName($form->get('jobSeekerProfile')['lastName']->getData());
$JS->setJobSeekerUser($user);
$em->persist($user);
$em->persist($JS);
$em->flush();
$this->get('session')->getFlashBag()->add(
'success',
$this->get('translator')->trans('success_registration')
);
return $this->redirect($this->generateUrl('login'));
}
My question is, shouldn't the relationship id get saved as well using scenario 1
because rest of the data is getting saved so whats stopping the relationship id to get saved as well?
My question 2 is, if suppose the answer to above question is no then is scenario 2
the right approach, it does the job but is it the symfony way of doing things?
Upvotes: 0
Views: 644
Reputation: 48893
My physic abilities tell me that your user_id column in your job_seeker_profile table is null. Is that correct?
If so then the most likely problem is that you are not setting the relation between User and JobSeekerProfile.
class User {
public function setJobSeekerProfile($profile) {
$this->jobSeekerProfile = $profile;
$profile->setUser($this); // THIS is what you are missing
Upvotes: 1