使用laravel Groupby迭代集合

时间:2017-06-17 17:16:25

标签: php laravel laravel-5.3

我正在尝试迭代一个集合并存储每个groupby的记录('type')。目前它逐行存储所有单个记录,但我需要的预期行为是存储组总数。

dd()返回此信息。因此,我希望组的所有约会时间为SUM,然后存储组,.i.e Test = 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();      
}

2 个答案:

答案 0 :(得分:0)

希望我在这里理解你的问题,但我不确定你是否需要分组,因为该项已经按“组”排序,即测试,测试2等。这会有效:

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

应返回类似

的内容
['Test' => 5, 'Test2' => 8]

如果这不正确,您可以提供更多样本数据以及一个好结果的示例吗?

答案 1 :(得分: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
}
相关问题