[英]Access Item By Id in Symfony?
I have a controller in Symfony3. 我在Symfony3中有一个控制器。 All of the data is returned like this:
所有数据都返回如下:
[
{
"id": 13,
"name": "testing",
"entry_date": {
"date": "2017-12-20 15:23:59.000000",
"timezone_type": 3,
"timezone": "Europe/London"
},
"last_update": {
"date": "2017-12-20 15:23:59.000000",
"timezone_type": 3,
"timezone": "Europe/London"
}
},
{
"id": 30,
"name": "testing2",
"entry_date": {
"date": "2017-12-20 22:02:37.000000",
"timezone_type": 3,
"timezone": "Europe/London"
},
"last_update": {
"date": "2017-12-20 22:02:37.000000",
"timezone_type": 3,
"timezone": "Europe/London"
}
}
]
I am trying to return an individual item by their id. 我想通过他们的id返回一个单独的项目。 My method so far looks like this:
到目前为止我的方法看起来像这样:
/**
* @Method("GET")
* @Route("/item/{item_id}")
* @View()
* @ApiDoc(
* resource = true,
* description = "Get an item record",
* section = "Spark DTR",
* )
*/
public function getItem($item_id)
{
$em = $this->getDoctrine()->getManager('app');
$mi_repo = $em->getRepository('AppBundle:Item')->find($item_id);
if(empty($mi_repo)) {
return new JsonResponse("Invalid Item ID", 404);
}
return new JsonResponse($mi_repo, 200);
}
However this method currently returns either "Invalid Item ID" (if there is no item, or 但是,此方法当前返回“无效的项ID”(如果没有项目,或
{}
if there is an item! 如果有物品! I want to return the contents of the item.
我想返回该项目的内容。 Grateful for your help,
感谢你的帮助,
With 同
$em->getRepository('AppBundle:Item')->find($item_id);
You're getting an object as a result, and JsonResponse() is expecting an array as a parameter. 你得到一个对象,JsonResponse()期望一个数组作为参数。
You've got a couple options here. 你有几个选择。 You can install the serializer component ( https://symfony.com/doc/3.4/components/serializer.html ) and serialize the object directly to Json and return that
您可以安装序列化程序组件( https://symfony.com/doc/3.4/components/serializer.html )并将对象直接序列化为Json并返回
$jsonContent = $serializer->serialize($mi_repo, 'json');
OR if you don't want to set up the serializer, you can also use the Doctrine Query Builder with getArrayResult() to return an array instead of an object 或者如果您不想设置序列化程序,您还可以使用带有getArrayResult()的Doctrine Query Builder来返回数组而不是对象
$query = $em->createQueryBuilder()
->select('p')
->from('Products', 'p')
->where('p.id= :item_id')
->setParameter('id', $item_id)
->getQuery();
$mi_repo = $query->getArrayResult();
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.