php – How to make two WHERE clauses inside a nested WITH

Question:

I have the following code snippet

$sectors = Sector::where('company_id', $id)
                 ->where('status', '0')
                 ->with('charges.levels')
                 ->get();

and i need 3 conditions

  • Sector status is 0
  • Cartoon status is 0
  • Levels status be 0

So I would like to know:

  • How do I use a WHERE that looks for charge 0 status and levels 0 status when they are in a nested with : ->with('charges.levels')

The code follows the hierarchy of that:

  • An industry has one or more jobs and a job belongs to only one industry.
  • A job has one or more levels and a level belongs to one job only.

Taking into account that I want to bring all levels where the level is status 0, the position is status 0 and the sector is status 0

Answer:

A very clear example on the site is that you can use conditions in advance , for example:

$users = App\User::with(['posts' => function ($query) {
    $query->where('title', 'like', '%first%');
}])->get();

in your code would be like this:

$sectors = Sector::where('company_id', $id)
             ->with(['charges' => function ($query) {
                   $query->where('status', 0);
                  },'charges.levels' => function($query) {
                    $query->where('status', 0);
                  }])
             ->get();

Ref. Eloquent: Relationships – Constraining Eager Loads

Scroll to Top