why would benefits have to be a great-grandchild, just make it a child of company.
Eloquent query for great-grandchildren?
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?
Laravel has no native support for a direct relationship.
I've created a package for this case: https://github.com/staudenmeir/eloquent-has-many-deep
You can use it like this:
class Company extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function benefits()
{
return $this->hasManyDeep(Benefit::class, [Department::class, Employee::class]);
}
}
$benefits = $company->benefits()->where('starts_on', '>=', '2019/01/01')->get();
Please or to participate in this conversation.