Your question doesn't really specify how you want to determine the top products. By the average rating?
Aug 6, 2018
10
Level 3
Get top review products?
I have problem with getting the top selling products.
I have 2 tables, products, and product_reviews
- products(id, name, price)
- product_reviews(id, product_id, rating)
a product can has many product_reviews
==============================
product
==============================
id | Name | price
----------------------------------------------
1 | Book . | 100
2 | Sock | 5000
3 | Strape | 9000
==============================
product_reviews
==============================
id | product_id | rating
---------------------------------------------
1 | 1 | 4
2 | 1 | 5
3 | 2 | 5
4 | 1 | 3
5 | 2 | 4
6 | 1 | 5
7 | 3 | 4
As you can see, the product with id 1 probaby has the most review and good review also.
How do I use eloquent to get the result?
Level 67
ProductReview::select('product_id')
->with('product')
->selectRaw('sum(rating) as rating')
->groupBy('product_id')
->orderBy('rating', 'desc')
->take(5)
->get();
So, that should get the top 5 product_reviews as determined by the total of their rating, along with the associated product.
If you want to get it by the average rating (instead of total), just change "sum" to "avg" in the selectRaw.
1 like
Please or to participate in this conversation.