return $this
->restaurant
->select('restaurants.*')
->selectRaw('COALESCE(ROUND(AVG(reviews.rating),1), 0) as average_rating')
->leftJoin('reviews', 'reviews.restaurant_id', '=', 'restaurants.id')
->when($user_id, function($query, $user_id){
$query->where("restaurants.user_id", $user_id);
})
->groupBy('restaurants.id')
->when($request->from_rating, function($query, $from_rating){
$query->having('average_rating', '>=', $from_rating);
})
->when($request->to_rating, function($query, $to_rating){
$query->having('average_rating', '<=', $to_rating);
})->orderByDesc("average_rating")
->paginate(
$this->perPage,
['id', 'name', 'image', 'description', 'filesystem', 'created_at'],
'page',
$request->page
);
这是我面临的查询。最后。我成功了但是现在的问题是看下面的行,
$ query->具有('average_rating','> =',$ from_rating);
这将引发错误:unknown column average_rating
。我不知道为什么。我在上面的选择中有此列。有人可以帮忙吗?
我还使用toSql()函数将其转换为sql语句。
结果:
select
`restaurants`.*,
COALESCE(ROUND(AVG(reviews.rating),1), 0) as average_rating
from
`restaurants`
left join `reviews` on `reviews`.`restaurant_id` = `restaurants`.`id`
group by `restaurants`.`id`
having `average_rating` >= ? and `average_rating` <= ?
order by `average_rating` desc
答案 0 :(得分:1)
SELECT
子句中不允许使用HAVING
子句中定义的列别名。这是由于RDBMS评估查询的不同部分的顺序而定:HAVING
子句在SELECT
子句之前进行求值,例如与ORDER BY
子句相反,稍后再处理(因此接受列别名)
您需要更改查询的这一部分:
$query->having('average_rating', '>=', $from_rating);
收件人:
$query->having('COALESCE(ROUND(AVG(reviews.rating),1), 0)', '>=', $from_rating);