Saad
Saad

Reputation: 1221

Laravel Eloquent self relation query to return nested JSON

I have a table with an one-to-one self relationship to represent an hierarchical structure. Below are the diagram of the Table and a few sample data:

Locations Table Example Data

This is the Location model code for the relationship:

class Location extends Model
{
    public function location()
    {
        return $this->hasOne('App\Location');
    }
}

I would like to query the Locations table and send a JSON response like the example below but I'm not sure how to approach the Query:

{
    "id": 1,
    "name": "Country",
    "location_id": null
    "location": {
        "id": 2,
        "name": "State",
        "location_id": 1
        "location": {
            "id": 3,
            "name": "City",
            "location_id": 2
        }
    }
}

Upvotes: 1

Views: 1285

Answers (1)

whmkr
whmkr

Reputation: 3075

To always eager load the location relation and not worry about depth, you could add the $with property to your location model:

protected $with = ['location'];

Now when you return a location, it will have all nested sub locations loaded up:

return App\Location::find(1);

Laravel also handles returning this as JSON if it's returned from a controller method.

as pointed out by Kyslik, this presents a potential N+1 problem, potential depth along with query size and the rest of the environment should be considered when deciding to use a solution like this in production, for something like locations, it's probably not an issue and well worth the simlpicity

Upvotes: 2

Related Questions