BaDr Amer
BaDr Amer

Reputation: 920

Join 3 database tables to get JSON Result in laravel

I have 3 database tables : Country,City and Restaurant

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

how can I retrieve country info with it's cities and it's restaurants ?

I'm using this code to get the countries with it's cities: note that I made all relationships between the tables as follows:

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

Result:

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

what shall I do to get the restaurants in each city in the same JSON response?

any help would be appreciated.

Upvotes: 0

Views: 370

Answers (1)

Angad Dubey
Angad Dubey

Reputation: 5452

You can use hasManyThrough() to access distant relationships: https://laravel.com/docs/5.1/eloquent-relationships#has-many-through

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

then you can fetch it like so:

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

Upvotes: 2

Related Questions