Chris Schmitz
Chris Schmitz

Reputation: 20970

Access multiple levels of many to many children with Eloquent

I have a table structure with several many to many joins.

nodes -< node_template >- templates -< placeholder_template >- placeholder

I have my node, template, and placeholder models setup with belongsToMany methods to link the main tables through the join tables.

e.g.

public function byFileMakerIdWithTemplates($id){
    return $this->node->with('templates')->where('internal_id', '=', $id)->firstOrFail();
}

Is there a way of selecting multiple levels of child nodes using eloquent?

I.e., Is there a way that I can query for a specific node record and get the template child records AND the template's placeholder records? Something like:

public function byFileMakerIdWithTemplates($id){
    return $this->node->with('templates')->with('placeholders')->where('internal_id', '=', $id)->firstOrFail();
}

I know I could use the DB facade to write you the mysql query I would need to grab all of the data using JOIN clauses or write the code to find the node with all of it's templates and then foreach through each template to find the placeholders, but if there was a way to grab it all cleanly in a multidimensional array it would be fantastic.

Upvotes: 1

Views: 1262

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152980

You can eager load deeply nested relationships by using the . dot syntax:

with('relationA.relationB');

So you would write:

public function byFileMakerIdWithTemplates($id){
    return $this->node->with('templates.placeholders')->where('internal_id', '=', $id)->firstOrFail();
}

Upvotes: 1

Related Questions