我有一个来自 laravel excel
的导入函数,它有效,但现在我想在其上添加一个标题,但它不起作用,我的 Excel 工作表中只有 1 列,标题称为 单位类型
。
<?php
namespace App\Imports;
use App\UnitType;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class UnitTypesImport implements ToCollection, WithHeadingRow
{
protected $user_id;
protected $proj_id;
public function __construct($user_id, $proj_id)
{
$this->user_id = $user_id;
$this->proj_id = $proj_id;
}
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
$unit_types_count = UnitType::where('name', $row[0])->where('project_id', $this->proj_id)->count();
if ($unit_types_count == 0){
UnitType::create([
'name' => $row['unit_type'],
'created_by' => $this->user_id,
'project_id' => $this->proj_id,
]);
}
}
}
public function headingRow(): int
{
return 0;
}
}
当我尝试使用方法 WithHeadingRow
时,它现在给我一个错误,如下所示:
Undefined offset: 0
最佳答案
继续@thmspl的回答,
在行中使用$row['unit_type']
$unit_types_count = UnitType::where('name', $row[0])->where('project_id', $this->proj_id)->count();
而不是$row[0]
。
关于php - laravel Excel 导入在列上设置标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58316971/