Thursday, March 2, 2017

Laravel 5.4 - Eager Loading Grandchild with Constraints

I am attempting to eager load a two deep relationship (child and grandchild) with constraints on both. However, when I add a constraint to the grandchild it returns an empty array. What I have is the following:

$products = Category::with([
   'products' => function($q){ $q->addSelect(['product_name', 'product_desc'])},
   'products.productgroup' => function($q){ $q->addSelect(['price'])}
])->where('id', 1);

This returns the Category and the product constraints, but the productgroup is returned as an empty array.

If I run the following:

$products = Category::with(['products', 'products.productgroup'])->where('id', 1);

I get the expected return of all data including the productgroup data. It's only when I add the constraint to the products.productgroup that it returns an empty array. Is there something i'm missing here? Is it even possible to add constraints to the grandchild like this?

I can't find any similar issues on stack or the laravel forums and i'm stumped.




via Bill Dukelow

Advertisement