我正在努力获得特性为true的前三名用户。这是我的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');
}
但当没有特色用户时,我会得到一行空字段,而不是空数组:
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" } }
为什么会这样?我该怎么修?
这是因为您在查询中使用聚合(使用AVG),所以它总是会得到至少一行结果。
SELECT AVG(0) FROM user WHERE 0;
此查询将始终返回至少一行结果,而不是null
结果。
如果查询必须按原样继续,则可以在返回结果之前对结果进行筛选,检查用户是否为null,否则返回空数组。
return (null == $result[0]['user'] ? [] : $result);