我正在使用 Laravel 5.1 获取一组包含相关问题的类别。
我只需要嵌套问题的 ID,但要让 select
起作用,我需要指定连接列,也就是 category_id
:
$categories = Category::with(['questions'=>function($query){
$query->select('id', 'category_id');
}])->get();
这让我:
[
{
"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},
...
]
}, ...
]
如何让 questions : [
只包含 ID 而不是对象,所以它是:
[
{
"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 ...
]
}, ...
]
我尝试使用 map 收集并列出 ID。这不起作用:
$test = collect($categories)->map(function ($q) {
return collect($q)->lists('id')->toArray();
});
我更愿意在这里处理这个,所以我不需要在前端处理它。
这是一个简单的方法。
这里是根据你的数据复制的一个样本数据
[
{
"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}
]
}
]
这是PHP代码
# 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;
}
输出看起来像这样
[
{
"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
]
}
]
如果你使用 json_encode($categories) 为 JSON 格式
希望对您有所帮助。