Search code examples
symfonydoctrinemany-to-manysymfony5

Recover data from two classes into many to many


I have a User table and a Library table, the relationship between them are many to many.

So I have a user_library table.

I manage to add data to the Library table from User but I cannot recover the data afterwards.

I add them like this:

    $em = $this->getDoctrine()->getManager();
    $repoUser = $em->getRepository('App:User');
    $user = $repoUser->findOneBy(['token' => $token_user]);

    $library = new Library();
    $library->setIdBook($id_book);

    $user->addLibrary($library);
    $em->persist($library);
    $em->persist($user);
    $em->flush();

I thought that simply doing: $user->getLibrary()->getIdBook() would be enough but it is not the case.

How do you think I can get all the id_book that match the user?


Solution

  • The thing is that your getLibrary returns ArrayCollection, you need to specify which Library you exactly want

    $libararies = $user->getLibrary() // <- this returns ArrayCollection
    $library = $libraries->first() // <- return 1st element
    

    Based on this code you can do a search for example, or just use doctrine to fetch library with desired ID, user, whatever you need straight from the database
    EDIT
    Lets say you want all libraries that are in relation with user with ID = 4

    ... // your code
    $user = $this->getDoctrine()->getRepository('your user class')->find(4); // here we find your user from DB
    $libraries = $user->getLibrary() // here we get all libraries which are in relation with user #4, you might want to rename the function as it returns ArrayCollection of Libraries, not Library
    $bookIds = array();
    foreach($libraries as $library) {
        $bookIds[] = $library->getIdBook(); 
    }
    dump($bookIds); // all user #4 book ids
    die;