首页 文章

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

提问于
浏览
1

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

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

[{},{}]

我无法理解什么是错的,我将采取哪些措施来解决这个问题 . 我已经在我的controller.php的 Headers 中使用“使用Symfony \ Component \ HttpFoundation \ Response”和“使用Symfony \ Component \ HttpFoundation \ JsonResponse” .

谢谢你的帮助 !

1 回答

  • 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);
    

    而且您必须在实体中实现注释,以告诉序列化器要做什么 . 请参阅上面的链接 .

相关问题