2017-06-17 68 views
0

遍歷我試圖通過集合進行迭代,並存儲每個進行分組的記錄(「類型」)。目前它將逐行存儲所有單獨的記錄,但我需要的預期行爲是存儲組總數。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();  
} 

回答

0

希望我明白你的問題在這裏,但我不知道你的,因爲該項目的已經由「羣」分類需要組,即測試,Test2的,等等。將這項工作:

$collection->each(function($group, $appointments) { 
    return [$group => collect($appointments)->sum(function ($appointment) { 
     return $appointment->date1->diffInMinutes($appointment->date2); 
    }); 
}); 

這應該返回類似

['Test' => 5, 'Test2' => 8] 

如果你可以給更多的樣本數據和一個什麼樣的好成績看起來像一個例子,這是不正確?

+0

像下面結束了工作。 –

0

這是結束工作的解決方案。可能有一個更好的方法。在do stuff部分中,您將使用從以前的foreach返回的對象。

$appointments = Appointment::find($id) 
        ->get(); 

$aType = $appointments->groupBy('type'); 
     $invoice_total = []; 
    foreach($aType as $key => $value) 
     { 
      $duration = []; 
      foreach($value as $a) 
      { 

       $date1 = Carbon::parse($a->starts_at);  
       $date2 = Carbon::parse($a->ends_at);          
       $duration[] = $date1->diffInMinutes($date2)/60; //divide by 60 to return hours 

     } 

    $Item    = new AppItem;         
    $Item->type   = $aType->type;  
    $Item->total_hours = $totalhours; 
    $Item->save();  
} 

//other stuff 
}