0

How can I perform count(*) operation using Symfony2 Doctrine ORM ? Without knowing the Entity class name and fields.

I got query builder to my class and I want to perform count(*) action.

I am doing the following:

public function count(QueryBuilder $queryBuilder)
    {
        $countQuery = clone queryBuilder;
        $countQuery->select('count(*)');
        $countQuery->setParameters(queryBuilder->getParameters());


        return $countQuery->getQuery()->getSingleScalarResult();
    }

This returns the following error: [Semantical Error] line 0, col 13 near '*) FROM Acme\DemoBundle\Entity\Product': Error: '*' is not defined.

DQL looks like this: SELECT count(*) FROM Acme\DemoBundle\Entity\Product Acme\DemoBundle\Entity\Product ORDER BY name desc, description asc

Any ideas? How to do it without specifying the column name ?

Rob Baillie
  • 3,436
  • 2
  • 20
  • 34
vardius
  • 6,326
  • 8
  • 52
  • 97
  • You need to specify which field you want to count because you are use orm. – Hardik Solanki Dec 08 '14 at 09:45
  • So there is no way to go around without not telling the field name ? What when the id field is going to have other name ? – vardius Dec 08 '14 at 09:48
  • Yepp. you can do it using `count(id) as other`. – Hardik Solanki Dec 08 '14 at 09:50
  • But the problem is i will not know the entity class structure, fields name and so – vardius Dec 08 '14 at 09:51
  • check this link : http://stackoverflow.com/questions/12088026/how-would-i-do-mysql-count-in-doctrine2 – Hardik Solanki Dec 08 '14 at 09:52
  • i manage to do it without field name, just counting over the class name `select('count(' . $countQuery->getEntityManager()->getRepository($countQuery->getRootEntities()[0])->getClassName() . ')')` – vardius Dec 08 '14 at 10:18
  • For what it's worth, this is another way to do it: `$repository->createQueryBuilder('WHATEVER')->select('count(WHATEVER)');` (if you provide a name to the query builder, you can use it in the count). – Javier C. H. Dec 08 '14 at 11:04

0 Answers0