遍歷我試圖通過集合進行迭代,並存儲每個進行分組的記錄(「類型」)。目前它將逐行存儲所有單獨的記錄,但我需要的預期行爲是存儲組總數。laravel GROUPBY通過收集
DD()返回此。因此,我希望所有的約會時間爲一組進行總結,然後存儲組,.i.e測試= 5小時。 Test2 = 3小時。
Collection {#471 ▼
#items: array:2 [▼
"Test" => Collection {#460 ▼
#items: array:2 [▼
0 => Appointment {#463 ▶}
1 => Appointment {#464 ▶}
]
}
"Test2" => Collection {#450 ▼
#items: array:2 [▼
0 => Appointment {#465 ▶}
1 => Appointment {#466 ▶}
]
}
]
}
這裏是控制器代碼。
foreach($appointments as $appointment)
{
$duration = [];
$aType = $appointments->groupBy('type');
foreach($aType as $type)
{
$duration[] = $date1->diffInMinutes($date2);
}
$totalhours = array_sum($duration); //sum the hours
$Item = new AppItem;
$Item->type = $aType->type;
$Item->total_hours = $totalhours;
$Item->save();
}
像下面結束了工作。 –