2

I'm trying to get top 3 users who has featured property = true. Here's my EntityRepository:

public function getFeaturedCleaners()
{
    $baseQuery = $this->_baseCleanerQuery();

    return $baseQuery
        ->where($baseQuery->expr()->eq('c.featured', $baseQuery->expr()->literal(true)))
        ->andWhere($baseQuery->expr()->isNotNull('c.user'))
        ->orderBy('ratingTotal', 'DESC')
        ->setMaxResults(3)
        ->getQuery()->getArrayResult();
}

private function _baseCleanerQuery()
{
    return $this->createQueryBuilder('c')
        ->select([
            'c as user',
            'COALESCE(AVG(rv.speed), 0) as ratingSpeed',
            'COALESCE(AVG(rv.quality), 0) as ratingQuality',
            'COALESCE(AVG(rv.responsibility), 0) as ratingResponsibility',
            'COALESCE((AVG(rv.speed) + AVG(rv.quality) + AVG(rv.responsibility)) / 3, 0) as ratingTotal',
        ])
        ->leftJoin('c.reviews', 'rv');
}

But when there's no featured users, I get one row with null fields, instead of empty array:

array(1) { [0]=> array(5) { ["user"]=> NULL ["ratingSpeed"]=> string(6) "0.0000" ["ratingQuality"]=> string(6) "0.0000" ["ratingResponsibility"]=> string(6) "0.0000" ["ratingTotal"]=> string(10) "0.00000000" } }

Why is it happening? How can I fix it?

1 Answer 1

1

This is because you are using aggregation in your query (with AVG), so it always will get at least a row with the result.

SELECT AVG(0) FROM user WHERE 0;

This query will always return at least 1 row with the result, not a null result.

If the query must continue as it is, you can filter the result before return it checking that the user is not null, otherwise return an empty array.

return (null == $result[0]['user'] ? [] : $result);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.