2017-03-02 97 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