Home » Php » php – Symfony2 & Doctrine – Get number of rows returned from datasource

php – Symfony2 & Doctrine – Get number of rows returned from datasource

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have the following code in my Symfony2 Repository Class…

$query = $this->createQueryBuilder('foo')
        ->where('foo.bar = :id')
        ->setParameter('id', $myID)
        ->getQuery();

How do I get the number of rows found by the database?

Thanks in advance

How to&Answers:

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

Answer:

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

Answer:

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 and setMaxResults. This method setFirstResult 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

Answer:

I think this is as concise as it gets:

$qb = $repo->createQueryBuilder('entity');
$qb->select('COUNT(entity)');

$count = $qb->getQuery()->getSingleScalarResult();

Where $repo is of type Doctrine\ORM\EntityRepository