加入 3 个数据库表以获得 JSON 结果 laravel
Join 3 database tables to get JSON Result in laravel
我有 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();
我有 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();