我有一个REST GET方法返回服务列表。通过在查询链接中提供参数,我希望能够对列表进行排序。例如:sort=price
-按价格升序排序,如果sort=-price
-按降序排序
查询如下:
http://127.0.0.1:8000/api/v1/services?sort=price
方法 public function searchAction(Request $request){
$sort = $request->query->get('sort');
$page = $request->query->getInt('page', 1);
$limit = $request->query->getInt('limit', 5);
$result = new JsonResponse();
$qb = $this->getDoctrine()->getRepository('AppBundle:Service')->createQueryBuilder('s');
if($sort != null){
if($sort == 'price'){
$qb->addOrderBy('s.price', 'ASC');
}
elseif($sort == '-price'){
$qb->addOrderBy('s.price', 'DESC');
}
}
$paginator = $this->get('knp_paginator');
$serviceListJson = $paginator->paginate(
$qb,
$page,
$limit
);
$result->setContent($serviceListJson);
return $result;
}
I get error
There is no component field [price] in the given Query (500 Internal Server Error)
服务实体class Service{
/**
* @var int
*
* @ORMColumn(name="id", type="integer")
* @ORMId
* @ORMGeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORMColumn(name="title", type="string")
*/
private $title;
/**
* @var int
*
* @ORMColumn(name="price", type="integer")
*/
private $price;
}
I am using KNP PAginator
bundle
我在配置中禁用了KNP bundle的sortable
特性。在查询中进行排序
knp_paginator:
default_options:
sort_field_name: ~ # Disable sorting
留待日后参考…: -)
如果您将传递表别名和您希望排序的字段,它将会工作。
:
http://127.0.0.1:8000/api/v1/services?sort=s.price
不是http://127.0.0.1:8000/api/v1/services?sort=price