Symfony JSON 输出包括字段名称
Symfony JSON output including field name
我正在尝试从我的数据库中的字段 'action' 中提取一个值,它是一个 JSON 字符串,但是我现在将它存储为一个值,就是这样:
'command'=>'get','target'=>'location'
然而,当我从数据库中提取它时,它包含我不想要的字段名称,见下文:
[{"action":"'command'=>'get','target'=>'location'"}]
我的代码在这里:
$em = $this->getDoctrine()->getManager();
$query = $em->createQueryBuilder();
$q = $query->select('z.action')
->from('AppBundle:ZeusUsers', 'z')
->where('z.id = ?1')
->setParameter(1, $id)
->getQuery();
$action = $q->getResult();
return new Response(json_encode($action));
所以我只需要知道如何抓取不包括字段名称的字段值?
您想使用 getSingleResult()
而不是 getResult()
来获取您的字段的值。如果没有找到结果或有多个结果,它将抛出异常(setMaxResults(1)
将补救这部分)。
https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L802
试试这个方法 getSingleScalarResult()
但请记住,如果它找不到任何东西,它将抛出异常
我正在尝试从我的数据库中的字段 'action' 中提取一个值,它是一个 JSON 字符串,但是我现在将它存储为一个值,就是这样:
'command'=>'get','target'=>'location'
然而,当我从数据库中提取它时,它包含我不想要的字段名称,见下文:
[{"action":"'command'=>'get','target'=>'location'"}]
我的代码在这里:
$em = $this->getDoctrine()->getManager();
$query = $em->createQueryBuilder();
$q = $query->select('z.action')
->from('AppBundle:ZeusUsers', 'z')
->where('z.id = ?1')
->setParameter(1, $id)
->getQuery();
$action = $q->getResult();
return new Response(json_encode($action));
所以我只需要知道如何抓取不包括字段名称的字段值?
您想使用 getSingleResult()
而不是 getResult()
来获取您的字段的值。如果没有找到结果或有多个结果,它将抛出异常(setMaxResults(1)
将补救这部分)。
https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L802
试试这个方法 getSingleScalarResult()
但请记住,如果它找不到任何东西,它将抛出异常