Api-platform request issue

这一生的挚爱 提交于 2019-12-24 19:26:51

问题


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:

  1. 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
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!