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.