2016-04-05 33 views
0

でJSONの結果を得るために3つのデータベースのテーブルを結合:それは都市だと、それはレストランだと国、市とレストラン私は3つのデータベーステーブル持ってlaravel

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()を使用することができます

答えて

2

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(); 
+0

おかげで、それが働きました。しかし、どのホテルをどの国の中でのみ得ることができます@ maximl337? ( "country"、 "="、 "US") - > get(); –

+0

'$ x = Country-> with(" city ") - >(" hotels " '$ホテル= $ x->ホテル; ホテルをも同様にフィルタリングしたい場合 '$ hotels = $ x-> hotels() - > where(" city_id "、" = "、15) - > get(); –

関連する問題