2017-06-17 70 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 
}