是否可以将总计数与结果一起返回? 目前使用此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();
答案 0 :(得分:1)
我认为不可能,一次性获得结果和总计数,基本上是在幕后,学说执行两个查询:
首先获得物品:
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探查器中查看。
所以你几乎没有选择的选择:
返回数组或某种包装器对象
return array("count" => count($paginator), "items" => $paginator->getIterator()->getArrayCopy());
或者如果你真的需要那么为每个项目手动设置
$count = count($paginator);
$items = $paginator->getIterator()->getArrayCopy();
foreach($items as $item) {
$item->setCount($count);
}
或者为什么不直接返回$ paginator对象?
答案 1 :(得分:0)
您还可以使用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);
}