Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $newEntries = [];
- foreach ($budgetData as $budgetDataForEmployee) {
- $employeeId = $budgetDataForEmployee['employee'];
- foreach ($budgetDataForEmployee['hours'] as $post => $hours) {
- $newEntries[] = [
- 'order_id' => $order->id,
- 'post_id' => $post,
- 'employee_id' => (int) $employeeId,
- 'hours' => (int) $hours,
- ];
- }
- }
- // Get existing budget hours for this order
- $existingEntries = Hour::where('order_id', $order->id)->get();
- // Index by composite key: postId_employeeId
- $existingMap = $existingEntries->keyBy(fn ($item) => $item->post_id . '_' . $item->employee_id);
- $newMap = collect($newEntries)->keyBy(fn ($item) => $item['post_id'] . '_' . $item['employee_id']);
- $toInsert = [];
- $toUpdate = [];
- $toDelete = [];
- foreach ($newMap as $key => $newItem) {
- $newHours = $newItem['hours'];
- if ($newHours === 0) {
- // Mark for deletion if it exists
- if ($existingMap->has($key)) {
- $itemToDelete = $existingMap[$key];
- Assert::isInstanceOf($itemToDelete, Hour::class);
- $toDelete[] = $itemToDelete->id;
- }
- } elseif (!$existingMap->has($key)) {
- $toInsert[] = $newItem;
- } else {
- $existingItem = $existingMap[$key];
- Assert::isInstanceOf($existingItem, Hour::class);
- if ($existingItem->hours !== $newHours) {
- $existingItem->hours = $newHours;
- $toUpdate[] = $existingItem;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement