嗨,我正在尝试使用symfony2生成json作为响应。
这是我的密码。
/**
* @Route("/viewComments/{taskId}")
*
*/
public function viewCommentsAction($taskId)
{
$commentsList = $this->getDoctrine()->getRepository("AppBundle:Comments")
->findBy(array("task" => $taskId));
if (!$commentsList) {
throw $this->createNotFoundException("non comments to show");
}
$serializer = $this->get('serializer');
$json = $serializer->serialize(
$commentsList,
'json', array('groups' => array('group1'))
);
return new Response($json);
}
不幸的是,我得到了回复:
[[],[],[],[]]
有什么建议吗?
试试这个,创建一个文件:CommentRepository
class CommentRepository extends EntityRepository
{
public function findCommentsList($id)
{
$query = $this->getEntityManager()->createQuery('YOUR QUERY HERE');
...
return $query->getArrayResult();
}
}
正如您所看到的,我返回了一个数组,现在您可以看到响应上的值。稍后,更改操作控制器中的下一行:
...
$commentsList = $this->getDoctrine()->getRepository("AppBundle:Comments")
->findCommentsList($taskId));
...
注意:您应该用单数调用您的实体