我正在尝试上传文件,但当我进行导入时,我收到以下错误Undefined array key"idEvento";
当我用从头开始的数字处理它时,我不会得到任何错误,并插入数据库
事件模型
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Eventos extends Model
{
use HasFactory;
protected $fillable = [
'nombre',
'idEvento',
'idSede',
'inicio',
'fin',
'idModalidad',
'cupo',
'valor',
];
}
导入数据功能
public function importData(Request $request){
$file = $request->file('documento');
$validator = Validator::make(
array(
'file' => $file,
),
array(
'file' => 'file|max:5000|mimes:xlsx,xls',
)
);
if ($validator->fails()) {
return Redirect::to('conferencia/import');
}
$import = new EventosImport();
Excel::import($import, request()->file('documento'));
return view('conferencias.import', ['numRows'=>$import->getRowCount()]);
//return redirect()->to(url('conferencia'));
}
事件导入代码
<?php
namespace AppImports;
use AppModelsEventos;
use MaatwebsiteExcelConcernsToModel;
use MaatwebsiteExcelConcernsWithHeadingRow;
class EventosImport implements ToModel, WithHeadingRow
{
private $numRows = 0;
/**
* @param array $row
*
* @return IlluminateDatabaseEloquentModel|null
*/
public function model(array $row)
{
++$this->numRows;
return new Eventos([
'nombre' => $row['nombre'],
'idEvento' => $row['idEvento'],
'idSede' => $row['idSede'],
'inicio' => PhpOfficePhpSpreadsheetSharedDate::excelToDateTimeObject($row['inicio']),
'fin' => PhpOfficePhpSpreadsheetSharedDate::excelToDateTimeObject($row['fin']),
'idModalidad' => $row['idModalidad'],
'cupo' => $row['cupo'],
'valor' => $row['valor'],
]);
}
public function getRowCount(): int
{
return $this->numRows;
}
}
卓越的图像描述在这里
这比在控制器中而不是在模型中使用函数导入要好。阅读excel有时使用类似于:
$data = Excel::load($path, function($reader) {})->get();
if(!empty($data) && $data->count()){
foreach ($data->toArray() as $key => $value) {
if(!empty($value)){
foreach ($value as $v) {
$insert[] = ['title' => $v['title'], 'description' => $v['description']];
}
}
}
if(!empty($insert)){
Item::insert($insert);
return back()->with('success','Insert Record successfully.');
}
}