如何使用laravel/php手动映射集合并获取总量
我目前有API返回的以下json响应。我能用拉威尔的口才把它还给你。有几个用户,每个用户都有几个收据。收据具有类型和状态。我想尝试获取与类型和状态相关的每个收据的总金额。我能够使用 $this->user->with'receipts'->has'receipts'->get['id',name'] 我尝试过使用多种laravel collections方法,但仍然无法获得所需的响应如何使用laravel/php手动映射集合并获取总量,php,laravel,laravel-5,eloquent,Php,Laravel,Laravel 5,Eloquent,我目前有API返回的以下json响应。我能用拉威尔的口才把它还给你。有几个用户,每个用户都有几个收据。收据具有类型和状态。我想尝试获取与类型和状态相关的每个收据的总金额。我能够使用 $this->user->with'receipts'->has'receipts'->get['id',name'] 我尝试过使用多种laravel collections方法,但仍然无法获得所需的响应 [ { "id": 1, "name": "kent", "receipts": [
[
{
"id": 1,
"name": "kent",
"receipts": [
{
"id": 1,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 100
},
{
"id": 2,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 100
},
{
"id": 3,
"user_id": 1,
"type_id": 2,
"status": 1,
"amount": 50
},
{
"id": 4,
"user_id": 1,
"type_id": 2,
"status": 0,
"amount": 30
},
{
"id": 5,
"user_id": 1,
"type_id": 2,
"status": 0,
"amount": 30
},
{
"id": 6,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 20
},
{
"id": 7,
"user_id": 1,
"type_id": 1,
"status": 1,
"amount": 10
}
]
},
{
"id": 2,
"name": "allison",
"receipts": [
{
"id": 9,
"user_id": 2,
"type_id": 1,
"status": 0,
"amount": 20
}
]
}
]
我希望得到这个:
[
{
"id": 1,
"name": "kent",
"receipts": [
{
"performance and deleted": 220,
"performance and not deleted": 10,
"project and deleted": 60,
"project and deleted": 50
}
]
},
{
"id": 2,
"name": "allison",
"receipts": [
{
"performance and deleted": 20,
"performance and not deleted": 0,
"project and deleted": 0,
"project and not deleted": 0
}
]
}
]
我主要关心的是使用laravel收集方法和易于阅读的代码来获得预期的结果我认为这会有所帮助
$user->receipts->sum('amount');
通过这种方式,我相信您可以通过可读性好的代码获得预期的结果 我假设您有$users变量,该变量包含集合中的用户列表,并且可能已经加载了收据
// You need to name the keys as you desire. (I can't figure out the labels by the type_id and status numbers).
$statusPair = collect([
'performance and deleted' => [
'type_id' => 1,
'status' => 0,
],
'something' => [
'type_id' => 1,
'status' => 1,
],
'something 2' => [
'type_id' => 2,
'status' => 0,
],
'something 3' => [
'type_id' => 2,
'status' => 1,
],
]);
$data = $users->map(function ($user) use ($statusPair) {
$receipts = $user->receipts;
$sums = $statusPair->mapWithKeys(function ($pair, $statusLabel) use ($receipts) {
$filtered = $receipts;
foreach ($pair as $key => $value) {
$filtered = $filtered->where($key, $value);
}
$sum = $filtered->sum('amount');
return [
$statusLabel => $sum,
];
});
return [
'id' => $user->id,
'name' => $user->name,
'receipts' => $sums->toArray(),
];
});
请提供一些数据的数据库结构。我建议用户使用原始查询,而不是编写复杂的雄辩的方法,在那里您最终将使用用户原始!db数据是我上面的数据,高于预期值answer@VishalTarkar我怎样才能得到想要的结果?谢谢!foreach可以用each方法替换吗?什么是$pair和$statusLabel?foreach可以是每个,它们基本上是相同的。对于收据标签,如performance and deleted或performance and not deleted,您的要求并不明确,这就是$statusLabel在我的代码中的含义,因此我假设它们是由type_id和status对决定的。如果不是您想要的,您可以修改这些对。