I have 3 tables
- users
- products
- ratings
And 3 Models
- User
- Product
- Rating
Relationships
- Product belongsTo User
- User hasMany Rating
Now I want to fetch the products who's user have rating more than 2.
How to write a query?
You can use the whereHas()
method. For example
Suppose your ratings
table has a field rating
that stores the rating value, and that the relationships are named
users
ratings
Then you can attempt
$products = Product::whereHas('users.ratings', function($rating){
$rating->where('rating','>',2);
})->get();
You could also make a relation in your user Model with an hasManyThrough(Product::class, Rating::class) and after work with that.
have a look on laravel docs about eloquent to understand better how to make queries with it:
https://laravel.com/docs/7.x/eloquent
And Have a look in the relations section in the documentation to see how hasManyThrough works.
https://laravel.com/docs/7.x/eloquent-relationships#introduction