9

I need your help please. I have this SQL query :

SELECT * , COUNT( * ) AS count FROM mytable GROUP BY email ORDER BY id DESC LIMIT 0 , 30

But I would like to do this in Symfony2 with Doctrine and the createQueryBuilder(). I try this, but didn't work :

$db = $this->createQueryBuilder('s');
$db->andWhere('COUNT( * ) AS count');
$db->groupBy('s.email');
$db->orderBy('s.id', 'DESC');

Can you help me please ? Thanks :)

13bonobo
  • 91
  • 1
  • 1
  • 2
  • what do you mean with *didn't work*? How to `LIMIT` your Doctrine results was answered [here before](http://stackoverflow.com/a/7404238/1847340) – ferdynator Jul 14 '13 at 19:38

3 Answers3

8

You need to run 2 queries:

$db = $this->createQueryBuilder();
$db
    ->select('s')
    ->groupBy('s.email')
    ->orderBy('s.id', 'DESC')
    ->setMaxResults(30);

$qb->getQuery()->getResult();

and

$db = $this->createQueryBuilder();
$db
    ->select('count(s)')
    ->groupBy('s.email')
    //->orderBy('s.id', 'DESC')
    ->setMaxResults(1);

$qb->getQuery()->getSingleScalarResult();
4

I tried to use

$query->select('COUNT(DISTINCT u)');

and it's seem to work fine so far.

gorodezkiy
  • 3,299
  • 2
  • 34
  • 42
2
$db = $this->createQueryBuilder('mytable');
$db
    ->addSelect('COUNT(*) as count')
    ->groupBy('mytable.email')
    ->orderBy('mytable.id', 'DESC')
    ->setFirstResult(0)
    ->setMaxResults(30);
$result = $db->getQuery()->getResult();

Hope it helps even if it's an old stack

Raghav Rach
  • 4,875
  • 2
  • 16
  • 16
wasbaiti
  • 51
  • 4