Symfony2 & Doctrine - Get number of rows returned from datasource
You need to execute DQL to do something you want.
$query = $this->createQueryBuilder() ->from('foo', 'f') ->where('foo.bar = :id') ->setParameter('id', $myID) ->getQuery();$total = $query->select('COUNT(f)') ->getQuery() ->getSingleScalarResult();
I think you can do something like that:
$query = $this->createQueryBuilder() ->select('COUNT(f.id)') ->from('foo', 'f') ->where('foo.bar = :id') ->setParameter('id', $myID) ->getQuery();$total = $query->getSingleScalarResult();
You execute the query then get the results. When you have the results, you get the number of record by doing a count
on the results:
$results = $query->getResult();$resultCount = count($results);
If you are concerned with paging, like getting 25 records out of the total. Then, you have two choices.
You perform the query twice, one time to get total results, another time to retrieve only 25 results using the method
setFirstResult
andsetMaxResults
. This methodsetFirstResult
enable you to set the offset and the second,setMaxResults
, number of records. The following code will give you results ranging from 25 to 50, it's the second page if you use 25 records by page.$query->setFirstResult(25);
$query->setMaxResults(25);
You can check doctrine-extensions for Doctrine2 which have paginator support. These extensions have been made by one of the developer of Doctrine2. You can review these here.
Hope this help.
Regards,
Matt