8 months ago

Eager load relation, but remove the relations own eager loads and appends

Posted 8 months ago by michapietsch

Hey everybody,

I have legacy code with a Child model with quite some eager loads and appended attributes, and when I include it as a relation (via with()), I get n+1 problems. I couldn't get to "clean up" the children inside the with(), but I solved it like shown in the example. I suspect this could be simplified a lot!

Could somebody please give a hint?

Please note: It's not about eager loading the children with the parent. Instead the Child has its own eagerly loaded relations, and some appended attributes for which it reaches into its relations. There is my challenge: unset all the unnecessary stuff that comes with the children by default.

$parents = parent::query()
    // some conditions

$children = Child::whereIn('parent_id', $parents->modelKeys())
    // some conditions

$parents->each(function ($parent) use ($children) {
    $parent->setRelation('children', $children->filter(function ($child) use ($parent) {
        return $child->parent_id === $parent->id;

Please sign in or create an account to participate in this conversation.