I have a DB with employees:
id
name
manager_id
foreign key is manager id and pointing at id of the same table employees.
I would like to get the list of employees but only where the manager name is called 'MANAGER'.
I tried this but it is not working:
$employee_list = Employee::with(['manager' => function($query){
$query->where('name', 'MANAGER');
}]);
I guess it is not working because it is constraining the function that will replace the ids with the name.
How can I constrain on the whole result so that I take only the records where the manager_id points to the record with name = 'MANAGER'?
See my reply here. You'll want whereHas
.
$employee_list = Employee::whereHas('manager', function ($query) {
$query->where('name', 'MANAGER');
})->with('manager');
And yes, you're correct. The callback on with
only constrains which relations are retrieved, not the base table query.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community