我试图获得有特色属性= true的前三名用户。这是我的EntityRepository:
Option Explicit
但是当没有特色用户时,我会得到一行包含空字段,而不是空数组:
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');
}
为什么会这样?我该如何解决?
答案 0 :(得分:1)
这是因为您在查询中使用聚合(使用AVG),因此它总是至少会得到一行结果。
SELECT AVG(0) FROM user WHERE 0;
此查询将始终返回至少一行结果,而不是null
结果。
如果查询必须按原样继续,则可以在返回结果之前过滤结果,检查用户是否为空,否则返回空数组。
return (null == $result[0]['user'] ? [] : $result);