php – Doctrine 2选择count groupBy

我正在尝试使用唯一的uid检索多个行.

$qb->select('COUNT() as cnt')
            ->from($type, 'c')
            ->groupBy('c.organization, c.process_role, c.domain, c.year')
            ->getQuery()->getSingleScalarResult()

但它返回一组组计数.我该怎么写这个呢?

最后,这有效,但它有点难看

$count = $this->_em->createQuery( 'SELECT COUNT(c.id) FROM '.$type.' as c WHERE c.id IN ('
            . 'SELECT c1.id FROM ' . $type . ' c1 '
            . 'GROUP BY c1.organization, c1.process_role, c1.domain, c1.year)')
            ->getSingleScalarResult();

最佳答案 尝试将您的单个组拆分为addGroupBy函数:

$qb->select('COUNT(c) as cnt')
            ->from($type, 'c')
            ->groupBy('c.organization')
            ->addGroupBy('c.process_role')
            ->addGroupBy('c.domain')
            ->addGroupBy('c.year')
            ->getQuery()->getSingleScalarResult();

但实际上这确实会返回相同的东西,因为它只会将结果分组为这4个变量的唯一集合.您应该使用DISTINCT选择方法并计算结果行.

$rows = $this->getDoctrine()->getManager()
    ->createQuery(
        'SELECT DISTINCT c.organization, c.process_role, c.domain, c.year FROM ' . $type . ' c'
    )
    ->getArrayResult();
$count = count($rows);

这是我唯一可行的方法,因为DQL不支持任何替代策略(例如SELECT COUNT(*)FROM(SELECT DISTINCT …))

点赞