tid = $tid; } /** * Execute the job. * * @return void */ public function handle() { $this->import(); } /** * 导入数据 * @return false|void */ public function import() { $task = LibraryTask::query()->find($this->tid); $task->status = LibraryTask::STATUS_IN; $task->save(); $path = Storage::disk(config('admin.upload.disk'))->path($task->path); if (!file_exists($path)) { $task->status = LibraryTask::STATUS_FAIL; $task->message = '找不到文件'; $task->save(); Log::error('*************找不到文件***************'); Log::error($path); return false; } try { $config = ['path' => '']; $excel = new \Vtiful\Kernel\Excel($config); $excel->openFile($path) ->openSheet() ->setSkipRows(1); //处理数据 $data = []; Log::error('*************开始读取数据*****************'); while (($row = $excel->nextRow()) !== NULL) { $nums = count($row); if ($nums == 6) { list( $xh, $type_name, $source, $name, $link, $cover_path, ) = $row; $type = array_search($type_name, LibraryCategory::resourceTypeMaps); if (!$type) { Log::error("*************类型不对{$type_name}*****************"); continue; } $data[] = [ 'xh' => $xh, 'type' => $type, 'source' => $source, 'name' => $name, 'link' => $link, 'cover_path' => $cover_path, ]; } } Log::error("数据读取完成"); $n = count($data); Log::error("开始写入数据:共{$n}条"); //数据写入 DB::beginTransaction(); $total_nums = 0; foreach ($data as $i => $item) { $book = LibraryBook::query()->where('category_id', $task->category_id)->where('name', $item['name'])->where('resource_type', $item['type'])->first(); if ($book) { $book->fill([ 'category_id' => $task->category_id, 'name' => $item['name'], 'resource_type' => $item['type'], 'source' => $item['source'], 'body' => $item['link'], 'cover_path' => $item['cover_path']] ); $book->save(); continue; } LibraryBook::query()->create([ 'name' => $item['name'], 'category_id' => $task->category_id, 'resource_type' => $item['type'], 'source' => $item['source'], 'body' => $item['link'], 'cover_path' => $item['cover_path'], 'task_id' => $task->id, ]); $total_nums++; } DB::commit(); Log::error("-----------完成---------------"); $task->status = LibraryTask::STATUS_SUCCESS; $task->message = "共读取{$n}条,共导入{$total_nums}条。"; $task->save(); } catch (\Exception $exception) { DB::rollBack(); $task->status = LibraryTask::STATUS_FAIL; $task->message = $exception->getMessage(); $task->save(); Log::error($exception); } } }