【发布时间】:2022-01-21 12:46:48
【问题描述】:
我有一个集合“功能”,每个都有一个“功能组”。 1 个功能 belongsToMany 功能组。
1 个功能 belongsToMany 汽车,因此它本身就是一个子集合。在我的汽车视图中,我想对功能进行分组。我该怎么办?
示例集合:
[
{
"id":1,
"group_id":1,
"name":"metallic",
"pivot":{
"car_id":1,
"feature_id":1
},
"group":{
"id":1,
"name":"paint"
}
},
{
"id":2,
"group_id":1,
"name":"blue",
"pivot":{
"car_id":1,
"feature_id":2
},
"group":{
"id":1,
"name":"paint"
}
},
{
"id":5,
"group_id":2,
"name":"gps",
"pivot":{
"car_id":1,
"feature_id":5
},
"group":{
"id":2,
"name":"interior"
}
},
{
"id":6,
"group_id":2,
"name":"leather seats",
"pivot":{
"car_id":1,
"feature_id":6
},
"group":{
"id":2,
"name":"interior"
}
}
]
想要的结果应该是这样的:
[
{
"id":1,
"name":"paint",
"features":[
{
"id":1,
"group_id":1,
"name":"metallic"
},
{
"id":2,
"group_id":1,
"name":"blue"
}
]
},
{
"id":2,
"name":"interior",
"features":[
{
"id":5,
"group_id":2,
"name":"gps"
},
{
"id":6,
"group_id":2,
"name":"leather seats"
}
]
}
]
在我的控制器中,我正在尝试使用each() 循环和mergeRecursive() 创建一个新集合,如下所示:
$car = Car::where('slug', $slug)->first()->load('features.group');
$newCollection = collect(["group 1" => "feature 1"]);
$car->features->each(function ($item, $key) use($newCollection) {
$current = collect([
$item->group->name => $item->name,
]);
$newCollection->mergeRecursive($current);
});
dd($newCollection);
return view('pages.car', [
'car' => $car,
'features' => $newCollection,
]);
我的集合中唯一的数据是我实例化它的虚拟数据。我错过了什么?
有什么建议吗?谢谢!
【问题讨论】:
标签: laravel eloquent laravel-8