【发布时间】:2019-03-21 08:52:27
【问题描述】:
我正在使用 Laravel Excel 包来处理批量上传。虽然我能够成功上传数据,但我的 Web 控制台显示“staff_id”没有默认值的错误。我试图将此作为异常捕获,但这不会被触发。我正在使用 ToModel 导入,如下所示
class EmployeesImport implements ToModel, WithHeadingRow
{
public function model(array $row)
{
try {
return new Employee([
'staff_id' => $row['staff_id'],
'first_name' => $row['first_name'],
'middle_name' => $row['middle_name'],
'last_name' => $row['last_name'],
'national_id' => (string) $row['national_id'],
'department_id' => 1,
]);
} catch (\Exception $e) {
dd($e->getMessage(), $row);
}
}
}
导入的 CSV 文件结构如下
在我的控制器中,我有这个来执行上传/导入
Excel::import(new EmployeesImport(), request()->file('bulk'));
最后,这是我的员工模型,显示可填写的字段
class Employee extends Model
{
use SoftDeletes;
protected $table = "employees";
protected $fillable = [
"staff_id", "first_name", "middle_name", "last_name", "national_id", "department_id", "avatar"
];
}
(最后一件事)如果它可能具有相关性 - 我的迁移文件的 up 方法
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('staff_id')->unique();
$table->string('first_name');
$table->string('middle_name')->nullable();
$table->string('last_name');
$table->string('national_id')->unique();
$table->unsignedBigInteger('department_id');
$table->longText('avatar')->nullable();
$table->timestamps();
$table->softDeletes();
//Foreign keys
$table->foreign('department_id')->references('id')->on('departments')->onDelete('cascade');
});
}
【问题讨论】:
-
关于我看到的文档 Excel::import(new UsersImport, 'users.xlsx');在您的代码中,我看到您将 as new UsersImport() 用作函数,使用其中一个或另一个有什么区别
-
这应该没问题,在这种情况下两种语法应该以相同的方式工作