baum icon indicating copy to clipboard operation
baum copied to clipboard

Eager loading related models

Open netm opened this issue 10 years ago • 4 comments

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

netm avatar Feb 19 '15 07:02 netm

Yep i'm looking for the same thing.

sidis405 avatar Mar 02 '15 14:03 sidis405

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.

etrepat avatar Mar 04 '15 18:03 etrepat

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.

etrepat avatar Mar 04 '15 20:03 etrepat

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?

lgt avatar Sep 18 '17 12:09 lgt