Getting relationship relationships using Eloquent in Laravel

I have a database with the following tables and relationships:

Advertising 1-1 Car m-1 Model m-1 Brand

If I want to get an ad, I can simply use:

 Advert::find(1); 

If I need car parts, I can use:

 Advert::find(1)->with('Car'); 

However, if I also need a model detail (after the relationship with Car), what the syntax will be, the following will not work:

 Advert::find(1)->with('Car')->with('Model'); 

Many thanks

+15
source share
2 answers

This is in the official documentation under "Eager Loading"

A few relationships:

 $books = Book::with('author', 'publisher')->get(); 

Nested Relationships:

 $books = Book::with('author.contacts')->get(); 

So for you:

 Advert::find(1)->with('Car.Model')->get(); 
+35
source

First you need to create your relationship,

 <?php class Advert extends Eloquent { public function car() { return $this->belongsTo('Car'); } } class Car extends Eloquent { public function model() { return $this->belongsTo('Model'); } } class Model extends Eloquent { public function brand() { return $this->belongsTo('Brand'); } public function cars() { return $this->hasMany('Car'); } } class Brand extends Eloquent { public function models() { return $this->hasMany('Model'); } } 

Then you just need to access this path:

 echo Advert::find(1)->car->model->brand->name; 

But your table fields will be like this because Laravel guesses that they are:

 id (for all tables) car_id model_id brand_id 

Or you will need to indicate them in relation.

+1
source

All Articles