Quantcast
Channel: Active questions tagged symfony4 - Stack Overflow
Viewing all articles
Browse latest Browse all 3924

Symfony 4 MongoDB ODM One to ONe relationship is not working

$
0
0

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

User Class:

/** * @MongoDB\Document * @MongoDBUnique(fields="email") */class User implements UserInterface{    /**     * @MongoDB\Id     */    private $id;    /**     * @MongoDB\Field(type="string")     */    private $firstName;    /**     * @MongoDB\Field(type="string")     */    private $lastName;    /**     * @MongoDB\Field(type="string")     * @Assert\NotBlank()     * @Assert\Email()     */    private $email;    /**     * @MongoDB\ReferenceOne(targetDocument=Work::class)     */    private $work;    //getter setter

Work Class:

class Work{    /**     * @MongoDB\Id()     */    private $id;    /**     * @MongoDB\ReferenceOne(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('test123@gmail.com');        $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.


Viewing all articles
Browse latest Browse all 3924

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>