dollar dollar - 5 months ago 43
SQL Question

Access all data from multiple Linked Tables in Laravel 5.2

enter image description here

Now In all the 4 models i have provided relations as

hasmany()
and
belongsTo()
.

When I tried to access a particular city from the table and it's associated state using below code it's working fine.

$citydetails=City_table::with('states')->find($id);


Now at the same time I also want to access the associated country name for the state. I tried doing this:

$citydetails=City_table::with('states','countries')->find($id);


This gives me an error message, I know this way it wont work because city and country are not related to each other directly, but I need to access data like this, if I access a specific city then I want it's state as well as it's country in the result.

Answer

You can use dot notation to access nested relationships. To quote the Laravel Documentation.

To eager load nested relationships, you may use "dot" syntax. For example, let's eager load all of the book's authors and all of the author's personal contacts in one Eloquent statement:

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

In your case, this would look something like:

 $citydetails = City_table::with('states.countries')->find($id);
Comments