是否可以与结果一起返回总数?当前使用此DQL查询以获取我的数组结果,但我还需要返回每个结果的总数。
$dql = "SELECT a, a.id, a.status, a.departDate, a.flightNum, a.departHour, a.arrivedHour, a.convocHour, a.convocPlace, a.customerPax, a.customerNote, a.providerPax,a.providerNote
FROM AppBundle:Assistance a GROUP BY a.id";
$query = $this->getEntityManager()->createQuery($dql)
->setFirstResult($skip)
->setMaxResults($take);
$paginator = new Paginator($query, $fetchJoinCollection = true);
$c = count($paginator);
dump($paginator->getIterator()->getArrayCopy());
return $paginator->getIterator()->getArrayCopy();
我认为不可能,获得结果并全部计数,基本上是在引擎盖下,学说执行两个查询:
第一个获取项目:
SELECT * FROM tbl
// and optional clausules
WHERE tbl.active = 1
GROUP BY tbl.type
ORDER BY tbl.rank
// taking one page
LIMIT 10
OFFSET 20
第二个用于计数:
SELECT COUNT(*) FROM tbl
// and optional clousules
WHERE tbl.active = 1
GROUP BY tbl.type
您可以在Symfony2 Profiler中检查。
因此,您几乎没有选择:
返回数组或某种包装对象
return array("count" => count($paginator), "items" => $paginator->getIterator()->getArrayCopy());
或为每个项目手动设置它,如果您真的需要
$count = count($paginator);
$items = $paginator->getIterator()->getArrayCopy();
foreach($items as $item) {
$item->setCount($count);
}
或为什么不返回$ paginator对象?
您也可以使用KnppaginatorBundle:
public function getItemsAction(Request $request)
{
$itemsQuery = $this->repository->getItems();
$current = $request->get('page', 1);
$limit = $request->get('limit', 10);
$pagination = $this->paginator->paginate($itemsQuery, $current, $limit);
$pagerResult = [
'count' => $pagination->getTotalItemCount(),
'items' => $pagination->getItems(),
'limit' => $pagination->getItemNumberPerPage(),
'current' => $pagination->getCurrentPageNumber()
];
return new JsonResponse($pagerResult);
}