symfony querybuilder group function

时间:2019-01-07 13:54:51

标签: symfony

i want get rows individually with condition that sum of prizes equals to my parameter (price) actually i want limit number of rows in prize entity but i get this error:

SQLSTATE[HY000]: General error: 1111 Invalid use of group function

this is my query :

$qb = $this->createQueryBuilder('up')
        ->join('up.prize','prize')
        ->select()
        ->where('up.user = :user')
        ->andWhere('SUM(prize.prizeValue) <= :price')
        ->setParameters(['user'=>$user , 'price'=>$price])
        ->getQuery()
        ->getResult();
    return $qb;

2 个答案:

答案 0 :(得分:0)

您不能在WHERE子句中使用聚合函数。

Why are aggregate functions not allowed in where clause

尝试一下:

$qb = $this->createQueryBuilder('up')
        ->join('up.prize','prize')
        ->select('up')
        ->where('up.user = :user')
        ->having('SUM(prize.prizeValue) <= :price') // Replace with `having`
        ->setParameters(['user'=>$user , 'price'=>$price])
        ->groupBy('up') // `Group by` because you're using an aggregate
        ->getQuery()
        ->getResult();
    return $qb;

答案 1 :(得分:0)

您必须将位置条件移到 HAVING 子句

$qb = $this->createQueryBuilder('up')
        ->join('up.prize','prize')
        ->where('up.user = :user')
        ->having('SUM(prize.prizeValue) <= :price')
        ->groupBy('up.id')
        ->setMaxResults(5);
        ->setParameters(['user'=>$user , 'price'=>$price]);

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