3

I am getting a set of categories with related questions using Laravel 5.1.

I want only the IDs of the nested questions, but to get the select to work, I need to specify the join column, aka category_id:

    $categories = Category::with(['questions'=>function($query){
        $query->select('id', 'category_id');
    }])->get();

This gets me:

[
 {
  "id": 1,
  "category": "Anatomy",
  "created_at": "2016-04-13 00:46:12",
  "updated_at": "2016-04-13 00:46:12",
  "questions":[
    {"id": 1, "category_id": 1},
    {"id": 2, "category_id": 1},
    {"id": 3, "category_id": 1},
    {"id": 4, "category_id": 1},
    ...
  ]
 }, ...
]

How can I get questions : [ to only contain the IDs instead of objects, so it'd be:

[
 {
  "id": 1,
  "category": "Anatomy",
  "created_at": "2016-04-13 00:46:12",
  "updated_at": "2016-04-13 00:46:12",
  "questions":[
     1, 2, 3, 4 ...
  ]
 }, ...
]

I've tried to collect using map and list the IDs. This does not work:

    $test = collect($categories)->map(function ($q) {
        return collect($q)->lists('id')->toArray();
    });

I'd prefer to handle this here so I don't need to deal with it on the frontend.

user3871
  • 12,432
  • 33
  • 128
  • 268

1 Answers1

2

Here is a simple way to do it.

Here is a sample data according to your data just replicate it

[
 {
  "id": 1,
  "category": "Anatomy",
  "created_at": "2016-04-13 00:46:12",
  "updated_at": "2016-04-13 00:46:12",
  "questions":[
    {"id": 1, "category_id": 1},
    {"id": 2, "category_id": 1},
    {"id": 3, "category_id": 1},
    {"id": 4, "category_id": 1}
  ]
 }
]

here is the PHP code

# JSON DATA
$data = '[
 {
  "id": 1,
  "category": "Anatomy",
  "created_at": "2016-04-13 00:46:12",
  "updated_at": "2016-04-13 00:46:12",
  "questions":[
    {"id": 1, "category_id": 1},
    {"id": 2, "category_id": 1},
    {"id": 3, "category_id": 1},
    {"id": 4, "category_id": 1}
  ]
 }
]';

# convert to array
# $data = json data
$categories = json_decode($data, true);

# assuming the categories has a list of object
# so i need to override it all
foreach ($categories as $key => $category) {

    # map a new array
    $list = array_map(function ($data) {
        return $data['id'];
    }, $category['questions']);
    # assign it to the current object being
    # iterated the new array created from
    # the array_map
    $categories[$key]['questions']  = $list;

}

the output will look like this

[
  {
    "id": 1,
    "category": "Anatomy",
    "created_at": "2016-04-13 00:46:12",
    "updated_at": "2016-04-13 00:46:12",
    "questions": [
      1,
      2,
      3,
      4
    ]
  }
]

if you make use of the json_encode($categories) to be in JSON FORMAT

Hope it helps.

Oli Soproni B.
  • 2,774
  • 3
  • 22
  • 47