Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bryceray1121's avatar

Nested Eager Loading With Constraints

With eager loading, how do I put a constraint on both a child and grandchild in the example below?

The child constraint works, just not sure how to also constrain on a column in the grandchild

$query->with([
        ’child.grandchild' => function ($q) {
            $q->where(’someCol', ’someVal’); //constraint on child
        $q->where(‘someOtherCol’, ‘someOtherVal’); //constraint on grandchild
        }
]);
0 likes
2 replies
Ricardo's avatar

With something like:

$query->with([
    'child' => function ($q) {
        $q->with(['grandchild' => function ($q) {
            $q->where(‘someOtherCol’, ‘someOtherVal’); //constraint on grandchild
        }])
        ->where(’someCol', ’someVal’); //constraint on child
    }
]);
10 likes
NoorDeen's avatar

**you can access your grand child by '.' relationship :

ie (child.grand-child)

$query->with([
    'child' => function ($q) {
        $q->where(’someCol', ’someVal’); //constraint on child
    },'child.grandchild' => function ($q) {
            $q->where(‘someOtherCol’, ‘someOtherVal’); //constraint on grandchild
    }
]);
9 likes

Please or to participate in this conversation.