4

I would like to know the number of row which are in my table TABLE and for which attribute name="joe"

Here the code I use so far but I retrieve the objects (which is just unnecessary, so not optimized)

$repository = $this->getDoctrine()->getManager()->getRepository('MyBundle:TABLE');
$name = "joe";
$liste = $repository->findBy(array('name' => $name));
$nombre = count($liste);

how can I achieved it with querybuilder using count? need to set parameter $name. All I ve seen so far have no parameter like this one, so do not know how this can work... (moreover I would like to avoid using paginator)

thanks.

Community
  • 1
  • 1
Alexis_D
  • 1,908
  • 3
  • 16
  • 35

1 Answers1

8

You can achieve it this way:

$repository = $this->getDoctrine()->getManager()->getRepository('MyBundle:TABLE');
$name = "joe";
$qb = $repository->createQueryBuilder('t');
$qb->select('count(t.id)');
$qb->where('t.name = :name');
$qb->setParameter('name', $name);
$nombre = $qb->getQuery()->getSingleScalarResult();

But good practice is to put this logic into repository class, so you can call method like this:

$nombre = $repository->countByName($name); 

Just create new method in your TableRepository class:

public function countByName($name)
{
    $qb = $this->createQueryBuilder('t');
    $qb->select('count(t.id)');
    $qb->where('t.name = :name');
    $qb->setParameter('name', $name);

    return $qb->getQuery()->getSingleScalarResult();
}
Mikhail Prosalov
  • 4,155
  • 4
  • 29
  • 41
  • Why would you use `count(t.id)` over `count('*')`? – Tvde1 Dec 08 '17 at 13:44
  • There shouldn't be a major performance difference in this case (when query have WHERE clause with non-indexed field). But yes, count(*) is a slightly better, for example in case of using MyISAM storage engine. – Mikhail Prosalov Dec 08 '17 at 14:47