Symfony 4 MongoDB ODM One to ONe relationship is not working

I am facing an error with symfony and mongoDB odm on one to one relationship
for example i have a user that has Work .

User Class:

/**
 * @MongoDBDocument
 * @MongoDBUnique(fields="email")
 */
class User implements UserInterface
{
    /**
     * @MongoDBId
     */
    private $id;

    /**
     * @MongoDBField(type="string")
     */
    private $firstName;

    /**
     * @MongoDBField(type="string")
     */
    private $lastName;

    /**
     * @MongoDBField(type="string")
     * @AssertNotBlank()
     * @AssertEmail()
     */
    private $email;


    /**
     * @MongoDBReferenceOne(targetDocument=Work::class)
     */
    private $work;
    //getter setter

Work Class:

class Work
{
    /**
     * @MongoDBId()
     */
    private $id;

    /**
     * @MongoDBReferenceOne(targetDocument=User::class)
     */
    private $user;


   //getter setter

}

Controller:

class TestingController extends AbstractController
{
    /**
     * @Route("/testing", name="testing")
     * @param DocumentManager $documentManager
     * @return Response
     * @throws MongoDBException
     */
    public function index(DocumentManager $documentManager)
    {
        $user = new User();
        $user->setFirstName('test1');
        $user->setLastName('test2');
        $user->setEmail('[email protected]');


        $documentManager->persist($user);

        $work= new Work();
        $work->setUser($user);

        $documentManager->persist($work);
        $documentManager->flush();

        return new Response("test");
    }

    /**
     * @Route("/test", name="test")
     * @param DocumentManager $documentManager
     * @return Response
     */
    public function test(DocumentManager $documentManager){
        $user = $documentManager->getRepository(User::class)->findAll();
        dump($user);

        return new Response("test test");
    }
}

So I created 2 classes one as user that has one work, I created the user , then I created a work and i assigned the user from the work class.
in MongoDB compass I got under Work collection a reference for the user.

now in the test method in the controller i try to find the users and dump the data.
The problem is whenever i want to find $user->getWork() i get a null value, while the user exists. but the inverse is working fine . whenever i try $work->getUser() i can find the user.

is there anything wrong in my code ? I want to use both methods : $user->getWork() and $work->getUser(),
I have tried adding to the ReferenceOne mappedBy and inversedBy but its always one of the two methods returns null value.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *