繁体   English   中英

使用laravel Groupby遍历集合

[英]Using laravel Groupby to iterate through collection

我试图遍历一个集合,并按groupby('type')存储一条记录。 目前,它逐行存储所有单个记录,但是我需要的预期行为是存储组总计。

dd()返回此值。 因此,我希望一个小组的所有约会时间都为SUM,然后存储该小组,即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();      
}

希望我在这里理解您的问题,但是我不确定您是否需要分组,因为该项目已经按“分组”进行了排序,即Test,Test2等。

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

那应该返回类似

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

如果这是不正确的,您能否提供更多示例数据,并举例说明一个好的结果?

这最终是可行的解决方案。 可能有更整洁的方法。 然后在“工作”部分中,处理从上一个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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM