Product::where('approved', '=', 1))->leftJoin('reviews', 'reviews.product_id', '=', 'products.id')->select('products.*', DB::raw('AVG(ratings) as ratings_average' ))->groupBy('id')->orderBy('ratings_average', 'DESC')->get()
This is a bit out of scope of your request, but if you have to query this often, I would opt for another way of working:
rating
to your model Product
created
on your model Review
Product
It'll make selecting your products and ordering them a lot faster. You can always cache them of course, but I would guess that you would be querying your products to show them to your customers a lot more often than a customer is adding a review...
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community