InnerDeviceImport.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Imports;
  3. use App\Exceptions\ImportError;
  4. use App\Models\DeviceName;
  5. use App\Models\InnerDevice;
  6. use App\Models\Option;
  7. use App\Models\Project;
  8. use App\Models\ProjectZone;
  9. use App\Models\Road;
  10. use App\Models\Spec;
  11. use App\Models\WorkPoint;
  12. use App\Models\Zone;
  13. use Illuminate\Support\Collection;
  14. use Illuminate\Support\Facades\Auth;
  15. use Illuminate\Support\Facades\Log;
  16. use Maatwebsite\Excel\Concerns\ToCollection;
  17. use PhpOffice\PhpSpreadsheet\Shared\Date;
  18. class InnerDeviceImport implements ToCollection
  19. {
  20. protected $model;
  21. protected $zone;
  22. protected $road;
  23. protected $project_zone;
  24. public function __construct()
  25. {
  26. $this->model = new InnerDevice();
  27. }
  28. public function formatDate($date)
  29. {
  30. if(empty($date)) return '';
  31. return Date::excelToDateTimeObject($date)->format('Y-m-d');
  32. }
  33. public function collection(Collection $rows)
  34. {
  35. if(count($rows) <= 1) {
  36. /** @noinspection PhpUnhandledExceptionInspection */
  37. // throw new ImportError('表格为空');
  38. return false;
  39. };
  40. foreach ($rows as $key => $row) {
  41. if($key == 0) continue;
  42. if(!isset($row[0])) break;
  43. $device_name = DeviceName::firstOrCreate([
  44. 'name' => $row[1]
  45. ]);
  46. $spec = Spec::firstOrCreate([
  47. 'device_name_id' => $device_name->id,
  48. 'name' => $row[2]
  49. ]);
  50. $work_point = WorkPoint::firstOrCreate([
  51. 'name' => $row[8]
  52. ])->first();
  53. $status = Option::where([
  54. ['table', '=', 'inner_devices'],
  55. ['column', '=', 'status'],
  56. ['name', '=', $row[9]]
  57. ])->first();
  58. $data = [
  59. 'number' => $row[0],
  60. 'device_name_id' => $device_name ? $device_name->id : '',
  61. 'spec_id' => $spec ? $spec->id : '',
  62. 'produce_date' => $this->formatDate($row[3]),
  63. 'buy_origin' => $row[4],
  64. 'manufacturer' => $row[5],
  65. 'shape' => $row[6],
  66. 'work_point_id' => $work_point ? $work_point->id : '',
  67. 'status' => $status ? $status->id : '',
  68. 'quantity' => (int)$row[7]
  69. ];
  70. $this->model->create($data);
  71. // $num = (int)$row[7];
  72. // for($i = 0; $i < $num; ++$i) {
  73. // $this->model->create($data);
  74. // }
  75. }
  76. return true;
  77. }
  78. }