Eloquent query for great-grandchildren?

Posted 4 months ago by algae14

Ok, so I have the following model hierarchy:

  • Companies have Departments.
  • Departments have Employees.
  • Employees have Benefits.

So, Benefits are great-grandchilden of Companies.

At the place in my code where I'm stuck, I have a particular instance of the Company model. And, I know that I can do the following with Eloquent to retrieve a given Company's Employees:

public function index(Company $company)
{
$employees = $company->hasManyThrough('App\Employees', 'App\Departments');
}

But, what I actually need for the particular $company instance are that company's Benefits. The only way I know how to do this is by looping through the $employees collection as follows:

public function index(Company $company)
{
    $employees = $company
                ->hasManyThrough('App\Employees', 'App\Departments');

    foreach ($employees as $employee) 
    {

        $company_benefits = $employee->benefits;

    }
}

More specifically, what I really need is to find the benefits that started after a certain date. So:

public function index(Company $company)
{
    $employees = $company
                ->hasManyThrough('App\Employees', 'App\Departments');

    foreach ($employees as $employee) 
    {

        $new_company_benefits = $employee->benefits->where('starts_on', '>=', '2019/01/01');

    }
}

Is there a way with Eloquent to do this that avoids having to do the whole foreach thing?

Please sign in or create an account to participate in this conversation.