Symfony2: request counter

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

Here is the code I am using so far, but I am retrieving 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 achieve this with querybuilder using count? you need to set the $ name parameter. Everything I've seen so far doesn't have a parameter like this , so I don't know how it might work ... (moreover, I would like to avoid using the paginator)

thank.

+3


source to share


1 answer


You can achieve this in the following 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 it's good practice to put this logic in the repository class, so you can call the method like this:



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

      

Just create a new method in the 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();
}

      

+8


source







All Articles