Support the ongoing development of Laravel.io →
Laravel Eloquent Database
Last updated 2 years ago.
0

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()

Last updated 7 years ago.
0

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:

  • add a field rating to your model Product
  • listen to the event created on your model Review
  • have that listener automatically recalculate the average rating (with the above query from @sylarbg for instance), and update your 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...

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Eli Mann Eli Mann emann95 Joined 22 Jun 2017

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.