mercredi 9 mai 2018

How to select specific fields from nested relations in Eloquent

I have the following query in Eloquent:

 public function firstSubsectionIdsOnly()
    {
        return $this->model->with(['sections' => function ($q) {
            $q->with(['subsections' => function ($q) {
                $q->first();

            }
            ])->first();
        }])->whereHas('sections.subsections')->first();
    }

This returns something like this:

   {
        "id": 1,
        "name": "Training exercise",
        "entry": "<p>sss</p>",
        "created_at": "2018-04-20 09:38:36",
        "updated_at": "2018-04-20 10:08:27",
        "sections": [
            {
                "id": 1,
                "subsections": [
                    {
                        "id": 2
                    }
                ]
            }
        ]
    }

I would like for it to only select the id fields for each relation so it should return something like this:

I have tried adding $q->select('id'); to the nested closure but that returns an empty subsections array.

Any idea on how I can achieve this? I am using Laravel 5.6



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire