【问题标题】:Symfony - findAll() returns ok if render, empty if responseSymfony - findAll() 如果渲染返回 ok,如果响应则返回空
【发布时间】:2017-12-04 14:37:54
【问题描述】:

我在我的 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);

.. 输出变成一个有 2 个孩子的空数组:

[{},{}]

!我不明白出了什么问题以及我将实施哪些更改来解决此问题。我已经在我的 controller.php 的标头中使用了“use Symfony\Component\HttpFoundation\Response”和“use Symfony\Component\HttpFoundation\JsonResponse”。

感谢您的帮助!

【问题讨论】:

标签: symfony doctrine-orm


【解决方案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);

你必须在你的实体中实现注解来告诉序列化器做什么。请参阅上面的链接。

【讨论】:

  • 完美,有效!序列化是我必须理解和研究的下一个主题;)谢谢。
  • 我会首先研究一下序列化程序对 Doctrine ArrayCollections 的处理情况,因为这是从您的存储库返回的内容。您可能能够序列化整个集合,或者您可能必须将每个实体序列化为一个新数组。祝你好运!
猜你喜欢
  • 2017-08-25
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2022-10-02
  • 1970-01-01
  • 2020-08-09
  • 2021-11-21
相关资源
最近更新 更多