首先,您在某些路线的路径中保留对作者的引用很奇怪
@Route("/api/authors/{authorId}").
建议:
我会考虑像这样使用 ORM 关系映射:
Book.php
/**
* @ORM\OneToMany(targetEntity="Author", mappedBy="book")
*/
private $authors;
作者.php
/**
* @ORM\ManyToOne(targetEntity="Book", inversedBy="authors")
* @JoinColumn(name="book_id", referencedColumnName="id")
*/
private $book;
然后为您服务:
$book = $entityManager->getRepository(App\Entity\Book::class)->find($id);
return $book;
然后在你的控制器中:
$book = $yourService->getBook($book_id);
return new JSONResponse($book);
然后在 JavaScript 中:
let bookJSON = JSON.parse(responseData);
let authors = bookJSON.authors;
解决办法:
AuthorRepository.php
/**
* @var $ids int[] array of author identifiers
*/
public function getAuthorsByIds(array $ids)
{
// it should return array of author entities
return $this->createQueryBuilder('author')
->select('author')
->where("author.id IN (?)")
->setParameter($ids)
->getQuery()
->getResult();
}
您的控制器
$book = $bookRepository->find($id);
$authorIdentificators = $book->getAuthors();
// convert routes to array of ids
array_walk($authorIdentificators, function(&$route) {
$route = explode('/', $route)[3];
});
$authors = $authorRepository->getAuthorsByIds($authorIdentificators);
// notice that your $authors private property is now array of objects (not array of strings(routes))
$book->setAuthors($authors);
return new JSONResponse($book); // now book JSON should have array of authors
你可以使用这个慢循环来代替存储库方法
$authors = $book->getAuthors();
// convert routes to array of entity objects:
array_walk($authors, function(&$route) {
$route = $authorRepository->find(explode('/', $route)[3]);
});