2016-04-05 27 views
0

I 3 Datenbank-Tabellen haben: Land, Stadt und RestaurantJoin 3 Datenbanktabellen JSON Ergebnis in Laravel zu bekommen

Country  {id,name} 
City  {id,name,country_id} 
Restaurant {id,name,city_id} 

wie kann ich Landes-Info abrufen damit Städte und es ist Restaurants?

ich diesen Code bin mit den Ländern zu bekommen, es Städte ist: beachten Sie, dass ich alle Beziehungen zwischen den Tabellen wie folgt hergestellt:

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

Ergebnis:

[ 
    { 
     "id": 1, 
     "name": "Spain", 
     "city": [ 
      { 
       "id": 1, 
       "name": "Madrid", 
       "country_id": 1 
      }, 
      { 
       "id": 2, 
       "name": "Barcelona", 
       "country_id": 1 
      } 
     ] 
    }, 
    { 
     "id": 2, 
     "name": "Italy", 
     "city": [] 
    } 
] 

Was soll ich Möchten Sie, dass die Restaurants in jeder Stadt dieselbe JSON-Antwort erhalten?

jede Hilfe wäre willkommen.

Antwort

2

Sie hasManyThrough() entfernte Verwandtschaften zugreifen können: https://laravel.com/docs/5.1/eloquent-relationships#has-many-through

// App\Country 
public function hotels() { 
    $this->hasManyThrough('App\Hotel', 'App\City'); 
} 

dann können Sie es wie so holen:

$x = Country::with('city')->with('hotels')->get(); 
+0

Dank, es funktionierte. Aber wie kann ich alle Hotels nur innerhalb eines Landes erreichen @ maximl337? –

+0

'$ x = Land-> mit (" Stadt ") -> mit (" Hotels ") -> wo (" Land "," = "," US ") -> get(); '$ hotels = $ x-> hotels; Wenn Sie auch Hotels filtern möchten '$ hotels = $ x-> hotels() -> where (" city_id "," = ", 15) -> get(); –