2017-03-02 29 views
0

我尝试使用如何使用knpPaginatorBundle和rest api?

公共职能listeleAction(请求$要求) {$ EM = $这个 - > getDoctrine() - > getManager();

$yasam_list=$em->getRepository("VanBundle:Yasam")->findAll(); 

    if (count($yasam_list)>0) 
    { 
    $yanit=array(); 
    foreach ($yasam_list as $meta) 
    { 
     $new_yasam=array(); 
     $new_yasam['id']=$meta->getId(); 
     $new_yasam['adi']=$meta->getAdi(); 
     $new_yasam['adres']=$meta->getAdres(); 
     $new_yasam['kategori_id']=$meta->getKategori()->getAdi(); 
     array_push($yanit,$new_yasam); 
    } 
     $paginator=$this->get('knp_paginator'); 

     $result= $paginator->paginate(
      $yanit, 
      $request->query->getInt('page',1), 
      $request->query->getInt('limit',10) 
     ); 

    }else{ 
     $yanit["success"] = 0; 
    $response["message"] = "Bu kategoriye en kısa sürede veri eklenecektir. "; 
    } 

    $response=new Response(json_encode(array('yasamlar' =>$result),JSON_UNESCAPED_UNICODE)); 
    $response->headers->set('Content-type','application/json; charset=utf-8'); 
    $response->setStatusCode(200); 
    return $response; 
} 

我的JSON输出

{ 
"yasamlar": {} 
} 

我怎样才能解决这个问题?感谢所有

+0

你为什么不使用分页的学说查询? –

回答

0

我解决

public function indexAction(Request $request) 
    { 

     $em=$this->getDoctrine()->getManager(); 
     //listelenecek bütün Yasam 
     $yasam_list=$em->getRepository("VanBundle:Yasam")->findAll(); 



     $pager=$this->get('knp_paginator'); 
     $paginated=$pager->paginate($yasam_list,$request->query->getInt('page',1), $request->query->getInt('limit',10)); 

     $factory=new KnpPaginatorFactory(); 
     $collection=$factory->createRepresentation($paginated,new Configuration\Route('yasamjson_index'),array()); 

     $serializer = $this->get('jms_serializer'); 
     $data = $serializer->serialize([ 
      'meta' => $collection, 
      'data' => $paginated->getItems() 
     ], 'json'); 


     return new Response($data); 

    } 
0

来分页之前,一些建议:

  • 使用KnpPaginatorBundle教义查询生成器一起。运行完整查询并从结果中分页并不能帮助即兴表演。
  • 对于REST API,您可以使用FosRestBundle。只需少量配置,您不必做json_encode,设置Content-TypeStatus Code
  • 如果您不想使用FosRestBundle。探索并尝试使用JsonResponse作为回报,而不是Response

现在,关于路过01​​信息,以API:

如果您正在使用FosRestBundle,您可以使用JMSSerializerBundle这将帮助你解析实体信息JSON的API响应。您可以进一步选择要显示的属性。分页数据将被自动分析。除此之外,您只需遍历KNPPaginator对象,您将获得表单原则查询构建器,并将分页和数据分别发送到JsonResponse

让我知道你是否需要代码片段。

希望这会有所帮助!

+0

感谢您的回答。我需要代码片段。请! – aziz

+0

我不使用FosRestBundle – aziz