php - Accessing Parent relations Laravel -
i have situation need iterate through models relationships (1 many) , call function on children. i.e.
$parent = parentclass::find(1) $children = $parent->children; foreach($children $child) { $child->function(); }
the function inside child needs access fields parent model. i.e.
public function function() { if($this->parent->attribute) return "true!"; return "false"; }
executing above, ends n+1 query problem. each child ends executing "select * parents id = 1".
i've had 3 thoughts on how fix this, though 2 of them feel awful, , last 1 doesn't seem great me, i'm asking there better solution have considered?
solution 1: eager load parent onto child models. i.e.
... $children = $parent->children; $children->load('parent'); foreach($children $child) ...
i think it's pretty obvious why awful, tremendous memory hog have parent model stored in memory n+1 times.
solution 2: pass parent child argument, i.e.
... foreach($children $child) { $child->function($parent); } ...
avoids memory issue of 1, still feels ugly. think child should know it's parent, , not need told through method args.
solution 3: add remember() child's parent relationship i.e.
public function parent() { return $this->hasone('parent')->remember(1); }
since children have same parent, cache query, , avoid calling every child. seems best of these 3 solutions, don't idea of having becomes mandatory on relationship.
is there better approach not considering? maybe better place include remember function?
thank you, -wally
if have inverse relationship defined like:
$parent = parentclass::find(1); foreach ($parent->children $child) { $requiredparentattr = $parent->attr; $child->function($requiredparentattr); // whatever else }
Comments
Post a Comment