0
votes

I have 3 tables

  1. users
  2. products
  3. ratings

And 3 Models

  1. User
  2. Product
  3. Rating

Relationships

  1. Product belongsTo User
  2. User hasMany Rating

Now I want to fetch the products who's user have rating more than 2.

How to write a query?

2

2 Answers

0
votes

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

  1. Product belongsTo User : relation name = users
  2. User hasMany Rating : relation name = ratings

Then you can attempt

$products = Product::whereHas('users.ratings', function($rating){
    $rating->where('rating','>',2); 
})->get();
0
votes

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