Skip to content
Advertisement

Laravel Eloquent how to get relationship self object?

I have tables with below relationship

housing_advertisements->housing_ad_near_places->near_places

And my HousingAdvertisement model has

public function nearPlaces()
{
    return $this->hasMany(HousingAdNearPlace::class);
}

and HousingAdNearPlace

public function nearPlace()
{
    return $this->hasOne(NearPlace::class, 'id');
}

when I make query like this:

HousingAdvertisement::with('nearPlaces.nearPlace')->where('user_id', '=', auth()->user()->id)->get();

I got HousingAdNearPlace object in HousingAdvertisement model:

[...
{
...,
"near_places": [
        {
            "id": 27,
            "housing_advertisement_id": 48,
            "near_place_id": 3,
            "created_at": "2021-06-29T12:23:35.000000Z",
            "updated_at": "2021-06-29T12:23:35.000000Z",
            "near_place": null
        },
        {
            "id": 28,
            "housing_advertisement_id": 48,
            "near_place_id": 4,
            "created_at": "2021-06-29T12:23:35.000000Z",
            "updated_at": "2021-06-29T12:23:35.000000Z",
            "near_place": null
        }
    ]
...]

How can I got self NearPlace model like this:

[...
{
...,
"near_places": [
        {
            "id": 3,
            "name": "Park",
            "slug": "park",
            "created_at": "2021-06-29T06:25:57.000000Z",
            "updated_at": "2021-06-29T06:25:57.000000Z"
        },
        {
            "id": 4,
            "name": "Beach",
            "slug": "beach",
            "created_at": "2021-06-29T06:25:57.000000Z",
            "updated_at": "2021-06-29T06:25:57.000000Z"
        }
    ]
...]

Advertisement

Answer

You need “Has Many Through” relationship on HousingAdvertisement

public function nearPlaces()
{
    return $this->hasManyThrough(NearPlace::class, HousingAdNearPlace::class);
}

And also define id keys as in ducumentation: https://laravel.com/docs/8.x/eloquent-relationships#has-many-through-key-conventions

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement