需求: 导入如下excel表单
先看官方文档 Row Validation 我的想法是,把业务都在model里处理,但有可能是导入的数据检测没问题,但对于业务来说,某项数据会有问题,比如一系列查询后该行数据已存在,需要统一返回到$import->failures()接收,找了官方文档里没有提到这事,所以便自行研究。。
app\Http\controllers下
$fileName = '绝对路径xxx';
$import = new SalarySheetImport();
$import->import($fileName);
pp($import->failures(), 'y');
app\Imports\SalarySheetImport.php
class SalarySheetImport implements ToModel, WithStartRow, WithValidation, SkipsOnFailure, WithCalculatedFormulas
{
public function model(array $row)
{
$currentRowNumber = $this->getRowNumber();
$month = $row[0];
$salaryBegin = $row[1];
$salaryEnd = $row[2];
$realName = $row[3];
if ($realName == '小陈') {
$failures = [];
$failures[] = new Failure(
$currentRowNumber,
3,
['错误了没啊'],
$row ?? [],
);
if ($this instanceof SkipsOnFailure) {
$this->onFailure(...$failures);
new RowSkippedException(...$failures);
}
}
$idcard = $row[4];
}
public function rules(): array
{
return [
'0' => [
'required'
],
'1' => [
'required',
],
'2' => [
'required',
],
'3' => [
'required'
],
'4' => [
'required',
'idcard'
],
];
}
public function customValidationMessages()
{
return [
'0.required' => '所属期间必须',
'0.date_format' => '所属期间格式有误',
'1.required' => '计薪范围开始必须',
'2.required' => '计薪范围结束必须',
'4.idcard' => '身份证格式有误',
];
}
}
先看WithValidation下获取的错误$import->failures() 再来看看模拟自定义错误+WithValidation后的打印:
|