首页 > 解决方案 > 在 laravel 中插入数组数据

问题描述

我正在以数组形式从数据库中获取此类数据。

Illuminate\Support\Collection {#1434
  #items: array:4 [
    0 => 20
    1 => 21
    2 => 22
    3 => 19
  ]
}

我想通过控制器为每个数组元素插入这个数组数据。

 foreach($plucked as $data){
    $attendant_data = new EmployeeAttendant();
    $attendant_data->user_id = $data;
    $attendant_data->date = Carbon::now()->format('Y-m-d');
    $attendant_data->time = Carbon::now()->format('H:i:s');
    $attendant_data->present = '0';
    $attendant_data->save();
 }

仅为第一个数组元素插入数据。

标签: phparrayslaravellaravel-query-builder

解决方案


只需准备数据并插入即可。

$insertableAttendant = [];
foreach($plucked as $data){
    $attendant_data = [];
    $attendant_data['user_id'] = $data;
    $attendant_data['date'] = Carbon::now()->format('Y-m-d');
    $attendant_data['time'] = Carbon::now()->format('H:i:s');
    $attendant_data['present'] = '0';
    $insertableAttendant[] = $attendant_data;
 }
EmployeeAttendant::insert($insertableAttendant);

推荐阅读