海工商新版后台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

120 lines
3.2 KiB

<?php
namespace App\Imports;
use App\Models\Config;
use App\Models\LoanStudentsList;
use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Model;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
use Illuminate\Support\Facades\DB;
HeadingRowFormatter::
default('none');
class LoanFirstSheetImport implements ToCollection, WithBatchInserts, WithChunkReading, WithHeadingRow, ToModel
{
private $round;
public function __construct(int $round)
{
$this->round = $round;
}
/**
* @param array $row
*
* @return Model|Model[]|null
*/
public function model(array $row)
{
// // 数据库对应的字段
return null;
}
public function collection(Collection $rows)
{
//导入的表格所有数据都在此处显示
$list = $rows->toArray();
if(empty($list)){
throw new \Exception("请勿上传空文件");
}
//取出当前年份
$config = Config::query()->where([
"unique_identification" => "annual_session"
])->first();
if(empty($config)){
throw new \Exception("相关配置信息不能为空");
}
//入库
$insertData = [];
foreach($list as $key => $item){
$arr = [
"sfzh" => trim($item["身份证"]),
"xh" => trim($item["学号"]),
"xm" => trim($item["姓名"]),
"fylx" => trim($item["费用类型"]),
"total" => trim($item["贷款总金额"]),
"is_five_year" => trim($item["五年一贯制"]),
"create_time" => time(),
"annual_session" => $config->data
];
array_push($insertData, $arr);
}
DB::beginTransaction();
try {
$chunk_list = array_chunk($insertData, 1000);
foreach ($chunk_list as $new_list) {
$add = LoanStudentsList::query()->insert($new_list);
if($add != count($new_list)){
throw new \Exception("导入数据失败,请重试");
}
}
DB::commit();
}catch (\PDOException $e){
DB::rollBack();
if ($e->getCode() === '23000') {
// 唯一性约束错误处理逻辑
$errorMessage = "导入表格中存在已入库学生贷款信息,请勿重复导入";
// 可以根据需要进行相关处理
throw new \Exception($errorMessage);
} else {
// 其他类型的错误处理逻辑
throw new \Exception("导入数据失败,请重试");
}
}catch (\Exception $e){
DB::rollBack();
throw new \Exception("导入数据失败,请重试");
}
}
//批量导入1000条
public function batchSize(): int
{
return 1000;
}
//以1000条数据基准切割数据
public function chunkSize(): int
{
return 1000;
}
}