Symfony - 如果呈现则findAll()返回ok,如果响应

时间:2017-12-04 14:37:55

标签: symfony doctrine-orm

我在Symfony 2.7网站上创建了一个自定义Bundle。 其中一个实体完美无缺:

  • 实体类是Version.php
  • 自定义存储库是VersionRepository

我的捆绑包的MainController.php是:

$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versions = $repository->findAll();

return $this->render('IpadUpdaterBundle:Version:index.html.twig', array(
'versions' => $versions
));

Twig中的输出是完美的:

  
      
  • 我的第一个版本行
  •   
  • 我的第二个版本行
  •   

但是......如果我想更改输出并使用相同的数据呈现JSON响应,我在控制器中进行此更改:

$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versions = $repository->findAll();

$versions = json_encode($versions);
$rep_finale = new Response($versions);
$rep_finale->headers->set('Content-Type', 'application/json');
return $rep_finale;

或:

$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versions = $repository->findAll();

return new JsonResponse($versions);

..并且输出变成一个有两个孩子的空数组:

  

[{},{}]

!我无法理解错误以及我将采取哪些措施来解决这个问题。我已经使用了#34;使用Symfony \ Component \ HttpFoundation \ Response"和"使用Symfony \ Component \ HttpFoundation \ JsonResponse"在我的controller.php的标题中。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

json_encode和JSONResponse不能很好地处理复杂的实体,尤其是与其他复杂实体的链接。大多数情况下,这些用于将字符串或数组编码为JSON。

如果您只需要实体中的某些信息,您可以创建一个数组并传递它。

$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versionInformation = $repository->getIdNameOfVersionsAsArray();
$versionInformation = array_column($versionInformation, 'id', 'name');

return new JSONResponse($versionInformation);

您必须在存储库中实现getIdNameOfVersionsAsArray函数才能返回值数组。

如果您需要版本实体的每个字段,则可能更容易使用序列化程序。 JMSSerializer Bundle是最受欢迎且受到良好支持的。

$serializer = $this->container->get('serializer');
$versionJSON = $serializer->serialize($versions, 'json');

return new Response($versionJSON);

您必须在实体中实现注释,以告诉序列化程序该做什么。请参阅上面的链接。