Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent

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'?

Last updated 2 years ago.
0

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.

Last updated 9 years ago.
0

That's great, it works. Thanks so much !!!

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.