C.Astraea
C.Astraea

Reputation: 185

Return count in result with doctrine paginator

Is it possible to return the total count along with the results ? Currently using this DQL query to get my array results but I also need to return a total count with each result.

   $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();

Upvotes: 1

Views: 6931

Answers (2)

Grzegorz
Grzegorz

Reputation: 74

I don't think is possible, to get results and total count in one go, basically under the hood, doctrine perform two queries:

First one to get items:

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

second one for count:

SELECT COUNT(*) FROM tbl
// and optional clousules 
WHERE tbl.active = 1 
GROUP BY tbl.type

You can check that in symfony2 profiler.

So you have few options to choose:

Return array or some kind of wrapper object

return array("count" => count($paginator), "items" => $paginator->getIterator()->getArrayCopy());

or set it manually for each item if you really need that

$count = count($paginator);
$items = $paginator->getIterator()->getArrayCopy();
foreach($items as $item) {
    $item->setCount($count);
}

or why don't just return $paginator object?

Upvotes: 1

d.garanzha
d.garanzha

Reputation: 813

You can also use 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);
}

Upvotes: 0

Related Questions