<?php
$query = $this->restaurant->leftJoin('reviews', 'reviews.restaurant_id', '=', 'restaurants.id');
$query = $user_id == null ? $query : $query->where("user_id", $user_id);
$query = $query->select('restaurants.*')
->selectRaw('ROUND(AVG(reviews.rating), 1) as average_rating')
->groupBy('restaurants.id')
->havingRaw('AVG(reviews.rating) >= ?', [$request->from_rating])
->havingRaw('AVG(reviews.rating) <= ?', [$request->to_rating])
->orderByDesc("average_rating")
->paginate(
$this->perPage,
['id', 'name', 'image', 'description', 'filesystem', 'created_at'],
'page',
$request->page
);
return $query;
My query looks like this. I have two tables: Restaurants and Reviews. The Reviews table stores restaurant_id
. The problem occurs when we have, for example, 10 restaurants and we have 1 Review only for one of the Restaurants. After running this query, only 1 restaurant is returned, because I use havingRaw
which filters Restaurants according to the average rating. So if a Restaurant doesn't have any rating, that Restaurant doesn't get returned.
How do I make that so all Restaurants still return, but their average rating becomes 0?