mardi 29 juin 2021

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"
        }
    ]
...]


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3hgFKb8
via IFTTT

Aucun commentaire:

Enregistrer un commentaire