-2

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?

yivi
  • 42,438
  • 18
  • 116
  • 138
Aexils
  • 33
  • 5
  • Something does not make sense here. If the relationship is "ManyToMany", which library would `getLibrary()` fetch? Wouldn't that be a collection? And how could a collection have an id? – yivi Jan 18 '20 at 19:22

1 Answers1

0

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;
B0re
  • 239
  • 1
  • 8
  • your method return only the first element. How to return all elements who correspond at my user? Also, when a user add the same data, this data is added to the database. I'm putting screenshots for you so you can understand. [My table User][1] [My table User_Library][2] [My table Libray][3] [1]: https://i.stack.imgur.com/WTOjV.png [2]: https://i.stack.imgur.com/ElZl8.png [3]: https://i.stack.imgur.com/iqJiu.png – Aexils Jan 19 '20 at 19:53
  • Editted my answer, give it a try – B0re Jan 19 '20 at 20:08