baum
baum copied to clipboard
Eager loading related models
Does anybody know if there is a way to use the Eloquent 'with' to eager load related models when using something like:
$tree = $root->getDescendantsAndSelf()->toHierarchy();
Many thanks
Yep i'm looking for the same thing.
Please note that when you call: $root->getDescendantsAndSelf()->...
you're already loading all the nested children in exactly one query, so there's no much meaning in using eager-loading in your example.
Having said that, If you wanted to eager-load the children relation on every query you could try to add to your model (which is rather aggressive):
...
protected $with = array('children');
...
Also, for that exact query of your example, something like:
$tree = $root->descendantsAndSelf()->with('children')->get()->toHierarchy();
will use Eloquent eager-loading mechanisms. I don't recommend this because you will hit the db twice instead of only once as I've said before.
Thinking of it... I may have misunderstood. If you want to load any related model (not children), you may use Eloquent eager-loading mechanisms as with other queries. F.Ex:
$tree = $root->descendantsAndSelf()->with('other-related', 'some.other')->get()->toHierarchy();
The last example should work as expected. ie: eager-loading other-related
& some.other
into each Baum\Node
instance. Sorry for the misunderstanding.
I try to get related model with the following code but I get no relation in output
$tree = \App\Group::where('id', $this->team_id)->with('leader')->first();
if($tree) {
$nodes = $tree->getAncestorsAndSelf();
return $nodes;
}
in my Baum model added
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function leader() {
return $this->belongsTo('App\User');
}
and in user model I have the hasMany method. Is the right way to bind related models?