Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving relationships of relationships using Eloquent in Laravel

I have a database with the following tables and relationships:

Advert 1-1 Car m-1 Model m-1 Brand

If I want to retrieve an Advert, I can simply use:

Advert::find(1); 

If I want the details of the car, I could use:

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

However, if I also want the detail of the Model (following the relationship with Car), what would the syntax be, the following doesn't work:

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

Many thanks

like image 408
Ben Thompson Avatar asked Sep 23 '13 15:09

Ben Thompson


People also ask

How does Laravel count Hasmany relationships?

Step 1: Place this code inside your 'Post' model. Step 2: Place this code inside your 'PostController' controller. $posts= Post::all(); return view('home')->with('posts', $posts); Step 3: Then count comments for all posts using the below code.

What is belongsTo in Laravel?

BelongsTo relationship in laravel is used to create the relation between two tables. belongsTo means create the relation one to one in inverse direction or its opposite of hasOne. For example if a user has a profile and we wanted to get profile with the user details then we can use belongsTo relationship.


1 Answers

It's in the official documentation under "Eager Loading"

Multiple relationships:

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

Nested relationships:

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

So for you:

Advert::with('Car.Model')->find(1); 
like image 199
Björn Avatar answered Oct 03 '22 03:10

Björn