我有 3 个数据库表:国家、城市和餐厅
Country {id,name}
City {id,name,country_id}
Restaurant {id,name,city_id}
如何检索国家/地区的城市和餐厅信息?
我使用此代码来获取具有城市的国家/地区: 请注意,我将表之间的所有关系设置如下:
Country {hasMany('City')}
City {hasMany('Hotel')}
City {belongsTo('Country')}
Hotel {belongsTo('City')}
$x = Country::with('city')->get();
return Response::json($x,200,[],JSON_PRETTY_PRINT);
结果:
[
{
"id": 1,
"name": "Spain",
"city": [
{
"id": 1,
"name": "Madrid",
"country_id": 1
},
{
"id": 2,
"name": "Barcelona",
"country_id": 1
}
]
},
{
"id": 2,
"name": "Italy",
"city": []
}
]
我该怎么做才能在相同的 JSON 响应中获取每个城市的餐馆?
如有任何帮助,我们将不胜感激。
最佳答案
您可以使用hasManyThrough()
来访问远程关系:
https://laravel.com/docs/5.1/eloquent-relationships#has-many-through
// App\Country
public function hotels() {
$this->hasManyThrough('App\Hotel', 'App\City');
}
然后你可以像这样获取它:
$x = Country::with('city')->with('hotels')->get();
关于mysql - 连接 3 个数据库表以在 Laravel 中获取 JSON 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36439111/