将数据从两个 类 恢复为多对多
Recover data from two classes into many to many
我有一个用户 table 和一个图书馆 table,它们之间的关系是多对多的。
所以我有一个 user_library
table.
我设法从用户那里向库 table 添加数据,但之后我无法恢复数据。
我是这样添加的:
$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();
我认为只需执行:$user->getLibrary()->getIdBook()
就足够了,但事实并非如此。
你认为我怎样才能获得与 user
匹配的所有 id_book
?
问题是你的 getLibrary returns ArrayCollection,你需要指定你到底想要哪个库
$libararies = $user->getLibrary() // <- this returns ArrayCollection
$library = $libraries->first() // <- return 1st element
基于此代码,您可以进行搜索,例如,或仅使用 doctrine 直接从数据库中获取具有所需 ID 的库、用户以及您需要的任何内容
编辑
假设您想要与 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;
我有一个用户 table 和一个图书馆 table,它们之间的关系是多对多的。
所以我有一个 user_library
table.
我设法从用户那里向库 table 添加数据,但之后我无法恢复数据。
我是这样添加的:
$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();
我认为只需执行:$user->getLibrary()->getIdBook()
就足够了,但事实并非如此。
你认为我怎样才能获得与 user
匹配的所有 id_book
?
问题是你的 getLibrary returns ArrayCollection,你需要指定你到底想要哪个库
$libararies = $user->getLibrary() // <- this returns ArrayCollection
$library = $libraries->first() // <- return 1st element
基于此代码,您可以进行搜索,例如,或仅使用 doctrine 直接从数据库中获取具有所需 ID 的库、用户以及您需要的任何内容
编辑
假设您想要与 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;