LinkImport.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace App\Imports;
  3. use App\Http\Models\Link;
  4. use App\Http\Models\LinkTaskDetail;
  5. use Illuminate\Support\Collection;
  6. use Maatwebsite\Excel\Concerns\Importable;
  7. use Maatwebsite\Excel\Concerns\ToCollection;
  8. class LinkImport implements ToCollection
  9. {
  10. use Importable;
  11. protected $siteId;
  12. public function __construct($siteId)
  13. {
  14. $this->siteId = $siteId;
  15. }
  16. const FIELD_MAP = [
  17. 0 => 'link_id',
  18. 1 => 'username',
  19. 2 => 'password',
  20. 3 => 'email',
  21. 4 => 'url',
  22. 5 => 'created_at'
  23. ];
  24. public function collection(Collection $collections)
  25. {
  26. $allLinks = Link::all();
  27. $all = collect([]);
  28. foreach ($collections as $key => $collection) {
  29. if ($key < 1 || empty($collection[0]) || empty($collection[2])
  30. || empty($collection[3]) || empty($collection[4])) {
  31. continue;
  32. }
  33. $matchLink = $allLinks->firstWhere('url', $collection[0]);
  34. if (!$matchLink) {
  35. continue;
  36. }
  37. $collection[0] = $matchLink->id;
  38. $temp = $this->fieldMap($collection);
  39. $all->push($temp);
  40. }
  41. $allRecords = $all->toArray();
  42. foreach ($allRecords as $record) {
  43. if (!LinkTaskDetail::query()->where([
  44. 'redundant_site_id' => $this->siteId,
  45. 'link_id' => $record['link_id'],
  46. 'enable' => 1,
  47. 'status' => 5
  48. ])->exists()) {
  49. LinkTaskDetail::query()->insert($record);
  50. }
  51. }
  52. // $allItems = $all->chunk(5000)->toArray();
  53. // foreach ($allItems as $item) {
  54. // LinkTaskDetail::query()->insert($item);
  55. // }
  56. }
  57. public function fieldMap($collect): array
  58. {
  59. $result = [];
  60. foreach ($collect as $inx => $val) {
  61. if (empty(self::FIELD_MAP[$inx])) continue;
  62. if (self::FIELD_MAP[$inx] == 'created_at') {
  63. $time = strtotime(str_replace('#', '', $val));
  64. $result[self::FIELD_MAP[$inx]] = $time ? date(' Y-m-d H:i:s', $time) : date('Y-m-d H:i:s');
  65. } else {
  66. $result[self::FIELD_MAP[$inx]] = $val;
  67. }
  68. $result['redundant_site_id'] = $this->siteId;
  69. $result['status'] = 5; //审核通过的
  70. $result['enable'] = 1;
  71. }
  72. return $result;
  73. }
  74. }