Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: count from the querybuilder

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.

like image 559
Alexis_D Avatar asked Oct 15 '25 03:10

Alexis_D


1 Answers

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();
}
like image 173
Mikhail Prosalov Avatar answered Oct 17 '25 08:10

Mikhail Prosalov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!