Keep in mind that the actual object must be saved by the EntityManager. Just providing a class as a reference to another class does not make entityManager aware that both classes exist.
You must save the actual userProfile for the EntityManager in order to be able to maintain the relationship.
UPDATE due to negative comment:
Please read the Doctrine docs ... You must persist!
The following example is an extension to the User-Comment example in this chapter. Suppose that in our application, the user is created whenever he writes his first comment. In this case, we will use the following code:
<?php $user = new User(); $myFirstComment = new Comment(); $user->addComment($myFirstComment); $em->persist($user); $em->persist($myFirstComment); $em->flush();
Even if you save a new user that contains our new comment, this code would not succeed if you removed the call to EntityManager # persist ($ myFirstComment). Doctrine 2 does not cascade the persist operation to all nested objects that are also new.
Update2: I understand what you want to achieve, but by design you should not move this logic inside your entities. Entities should represent as little logic as possible, since they represent your modal.
If that said, I think you could accomplish what you are trying to do as follows:
$user = new User(); $profile = $user->getProfile(); $objectManager->persist($user); $objectManager->persist($profile); $objectManager->flush();
However, you should consider creating a userService containing the entitymanager and make it responsible for creating, linking, and saving the user + userProfile object.
source share