简体   繁体   中英

Access all data from multiple Linked Tables in Laravel 5.2

在此处输入图片说明

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM