访问 Laravel 5.2 中多个链接表的所有数据
Access all data from multiple Linked Tables in Laravel 5.2
现在,在所有 4 个模型中,我提供的关系为 hasmany()
和 belongsTo()
。
当我尝试从 table 访问特定城市时,它使用下面的代码关联状态,它工作正常。
$citydetails=City_table::with('states')->find($id);
现在同时我也想访问州的相关国家名称。我试过这样做:
$citydetails=City_table::with('states','countries')->find($id);
这给了我一条错误消息,我知道这种方式行不通,因为城市和国家/地区彼此没有直接关系,但我需要这样访问数据,如果我访问特定城市,那么我希望它是结果中的州和国家/地区。
您可以使用点符号来访问嵌套关系。引用 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();
在你的情况下,这看起来像:
$citydetails = City_table::with('states.countries')->find($id);
现在,在所有 4 个模型中,我提供的关系为 hasmany()
和 belongsTo()
。
当我尝试从 table 访问特定城市时,它使用下面的代码关联状态,它工作正常。
$citydetails=City_table::with('states')->find($id);
现在同时我也想访问州的相关国家名称。我试过这样做:
$citydetails=City_table::with('states','countries')->find($id);
这给了我一条错误消息,我知道这种方式行不通,因为城市和国家/地区彼此没有直接关系,但我需要这样访问数据,如果我访问特定城市,那么我希望它是结果中的州和国家/地区。
您可以使用点符号来访问嵌套关系。引用 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();
在你的情况下,这看起来像:
$citydetails = City_table::with('states.countries')->find($id);