Laravel Collection groupBy multiple and average an element o



我在查询中成功地使用了groupBy来按两个元素分组。

这是代码:

AppGroupshot::findOrNew(4)
->load('snapshots.answers.question.tags','snapshots.participant')
->answers->groupBy([
function ($item, $key) {
return [$item->question->tags()->first()->name];
},
function ($item, $key) {
return [$item->participant->id];
},
]);

我以前在groupBy旁边使用过map((来对分组元素求和。在这种情况下,我想求出答案的分数(答案(。当上面使用时,我很难将这种方法应用于第二个分组集合。

也许是这样的:

->map(function ($row) {
return $row->first()->sum('answer');
});

如果我将以上应用于我的初始查询,我会得到:

=> IlluminateSupportCollection {#2542
all: [
"FEAR" => 6,
"RAGE" => 22,
"PANIC/GRIEF" => 2,
"PLAY" => 3,
],
}

我在找什么。。通过嵌套查询求和第二组。。。

=> IlluminateSupportCollection {#2542
all: [
"FEAR" => [Bob => 5, Bill => 2, Ben => 1 ],
"RAGE" => [Bob => 2, Bill => 1, Ben => 1 ],
"PANIC/GRIEF" => [Bob => 4, Bill =>3, Ben => 4 ],
"PLAY" => [Bob => 5, Bill =>3, Ben => 1 ],
],
}

非常感谢@Michael在评论中为我指明了方向。正如他所建议的,将其分解为多个部分有助于将第二个分组和总和封装在第二个映射中。

这是一件美丽的事情。这是代码:

AppGroupshot::findOrNew(4)
->load('snapshots.answers.question.tags', 'snapshots.participant')
->answers->groupBy([
function ($item, $key) {
return [$item->question->tags()->first()->name];
},
])
->map(function ($row) {
return $row
->groupBy([
function ($item, $key) {
return [$item->participant->FullName];
},
])
->map(function ($row) {
return $row->sum('answer');
});
});

以及结果

=> IlluminateSupportCollection {#4354
all: [
"FEAR" => IlluminateSupportCollection {#3670
all: [
"Gavin Ellis" => 6,
"Naomi Lloyd" => 10,
"Jonathan Walsh" => 18,
"Reece Kelly" => 17,
"Connor Wood" => 3,
"Keith Price" => 4,
"Joe Phillips" => 5,
"Bradley Clarke" => 6,
"Superadministrator Superadministrator" => 6,
"Elsie Reynolds" => 12,
],
},
"RAGE" => IlluminateSupportCollection {#3972
all: [
"Gavin Ellis" => 22,
"Naomi Lloyd" => 10,
"Jonathan Walsh" => 12,
"Reece Kelly" => 29,
"Connor Wood" => 13,
"Keith Price" => 10,
"Joe Phillips" => 17,
"Bradley Clarke" => 25,
"Superadministrator Superadministrator" => 6,
"Elsie Reynolds" => 10,
],
},

相关内容

最新更新