问题
I have two entities author and book
book | manytoOne |author
id | |id
idAuthor |
in the author controller i have an Action function that gets the author details and all his books (using the forward function to get the books)
public function authorDetailsAction($id){
$author= $this->getDoctrine()->getRepository(Author::class)->find($id);
$books= $this->forward('AppBundle:Book:authorBooks',array('id' => $id));
return array('author' => $author, 'books' => $books);
}
but it shows only author informations
or when im rutrning only the books return $books
i got this error
The controller must return a response (Array(0 => Object(AppBundle\Entity\Book), 1 => Object(AppBundle\Entity\Book), 2 => Object(AppBundle\Entity\Book)) given). (500 Internal Server Error)
Thanks in advance for any guidance
回答1:
As it looks like you use API Platform, you can achieve what you want without creating a custom controller:
- Add a filter to the
Author
resource to be able to search an author by name: https://api-platform.com/docs/core/serialization-groups-and-relations#embedding-relations - Embed books related to an author directly in the author response: https://api-platform.com/docs/core/filters#search-filter.
回答2:
A Symfony controller must always return an instance of the Symfony\Component\HttpFoundation\Response
class. You cannot simply return an arbitrary value, because Symfony wouldn’t know how to render it.
There are two ways to create a Response
object inside a controller:
First, direct instantiation. For example:
$response = new Response("This is my content.", 200);
$response->headers->set('Content-Type', 'text/plain');
return $response;
Second, if your controller is a child class of Symfony\Bundle\FrameworkBundle\Controller\Controller
, you can use the render()
method to access the templating engine:
$response = $this->render("foo/bar.html.twig", ["foo" => "bar"]);
$response->headers->set('Content-Type', 'text/plain');
return $response;
See https://symfony.com/doc/current/controller.html for more.
来源:https://stackoverflow.com/questions/45821480/api-platform-request-issue