sql无法找到未知列

时间:2019-03-30 11:13:00

标签: php sql laravel

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  

1 个答案:

答案 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);