devondahon
2 months ago
414
10
Laravel

Relationships - with() : Get list of objects instead of an array

Posted 2 months ago by devondahon

When using

return Pet::with('questions:code,color,size')->get();

I get an array of objects for the questions attribute.

  {
    "id": 1,
    "name": "Dog",
    "created_at": "2020-07-27T12:29:52.000000Z",
    "updated_at": "2020-07-27T12:29:52.000000Z",
    "questions": [
      {
        "code": " set1.question1 "
        "color": "A"
        "size": "134"
      },
      {
        "code": " set1.question2 "
        "color": "C"
        "size": "125"
      }
   ]
  }

Is there an option to get an object where code is the object key instead ?

  {
    "id": 1,
    "name": "Dog",
    "created_at": "2020-07-27T12:29:52.000000Z",
    "updated_at": "2020-07-27T12:29:52.000000Z",
    "questions": {
      "set1.question1" :
      {
        "color": "A"
        "size": "134"
      },
      "set1.question2":
      {
        "color": "C"
        "size": "125"
      }
   ]
  }

I'd probably need something similar to:

        return Pet::with('questions')
            ->get()
            ->map(function ($pet) {
                return $pet->questions->keyBy('code');
            });

But that's mapping the parent (professsion) instead of the children (questions).

Please sign in or create an account to participate in this conversation.