Search code examples
laraveleloquenteloquent-relationship

How to write Laravel 7 nested query?


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?


Solution

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