从 JsonResponse 对象内的 Doctrine 返回数据 [英] Return data from Doctrine inside a JsonResponse object
问题描述
我的问题是我想在 JsonResponse
对象中返回我从 Doctrine 获得的一些数据.我使用 QueryBuilder
获取数据,如下所示:
My problem is that I want to return some data that I get from Doctrine inside a JsonResponse
object. I get the data with a QueryBuilder
, like this:
$qb = $this->getDoctrine()->getRepository(User::class)->createQueryBuilder('u');
$data = $qb->getQuery()->getResult();
$JSONResponse = new JsonResponse();
$JSONResponse->setData($data);
然而,JsonResponse
里面的数据看起来是空的:
However, the data inside the JsonResponse
looks empty:
data: {
[],
[],
[],
[],
.....
}
有谁知道我如何以这种方式正确返回数据?
Does anyone know how I can return the data this way correctly?
推荐答案
我认为您使用 Doctrine 从数据库中正确获取了 User
数组(您可以使用简单的 <获取它们后的 code>var_dump($data).
I think you're getting the array of User
s correctly from the DB using Doctrine (you can check that with a simple var_dump($data)
after you fetch them.
但是,当您将 User
数组放入 JsonResponse
时,这些对象将被序列化,并且因为(我猜) 中的属性User
类是private
,每一个的序列化只是一个空数组[]
...
However, when your put you array of User
s into the JsonResponse
, those objects will be serialized, and since (I guess) the properties in the User
class are private
, the serialization of each one is just an empty array []
...
您需要将一个普通的数据数组传递给 JsonResponse
而不是 User
的数组,对此您有几个选择:
You need to pass a plain array of data to JsonResponse
instead of an array of User
s, for which you have a few options:
- 使用
$qb->getQuery()->getArrayResult()
直接获取普通数组而不是User
数组对象. - 使
User
类实现JsonSerializable
接口,因此您可以定义对象的序列化方式. - (推荐)使用一些专门的序列化库(如 JMS Serializer(或手动,如果您愿意),然后将该数据放入
JsonResponse
.
- Use
$qb->getQuery()->getArrayResult()
to get directly a plain array instead of an array ofUser
objects. - Make
User
class implementJsonSerializable
interface, so you define how the objects should be serialized. - (Recommended) Generate a plain array from your
User
objects using some specialized serialization library like JMS Serializer (or manually if you prefer), and then put that data into theJsonResponse
.
这篇关于从 JsonResponse 对象内的 Doctrine 返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!