php - 在 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();
}
仅为第一个数组元素插入数据。
解决方案
只需准备数据并插入即可。
$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);
推荐阅读
- laravel - 运行 2 个 composer.json 文件
- sql - Oracle - 按时间返回记录
- python - 使用 pydicom 添加新的私有条目密钥
- angular - 如果用户创建新文档,如何使用云功能将 Firestore 数据索引到 Algolia?
- python - 使用 pip 安装软件包后找不到 rabbitmq
- google-cloud-dataproc - 在初始化操作脚本中直接更新 Dataproc 集群(元数据或标签)
- java - 使用 JAXB 创建带有 XSD 的 XML
- ruby-on-rails - 在 Ruby on Rails 中,有没有比使用 eval() 动态访问这个 jsonb 更好的方法?
- python - python中的多处理池问题
- node.js - 安装较新版本的 node.js 后,Angular 项目无法正常工作