I’m trying to get the average rating of total star rating for one restaurant. The customers will rate this restaurant. I made a pivot table for storing customers ratings.
The average rating =5
-------- place_ratings --------------- user_id place_id rating 1 1 4 2 1 3 5 1 5
What is the formula or how can I calculate that in php laravel ?
This is my code:
public function placeRating($id) { $rates = PlaceRating::where('place_id',$id)->select('rating')->get()->toArray(); $rateArray =[]; foreach ($rates as $rate) { $rateArray[]= $rate['rating']; } $sum = array_sum($rateArray); $result = $sum/5; return response()->json(['rating'=>$result],200); }
Advertisement
Answer
Don’t take all place_ratings
records out, if there are thousands+ user rate the restaurant, it will slow your API.
Try to use this query:
PlaceRating::where('place_id',$id)->selectRaw('SUM(rating)/COUNT(user_id) AS avg_rating')->first()->avg_rating;