海南旅游SAAS
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.

63 lines
1.5 KiB

  1. <?php
  2. namespace App\Imports;
  3. use App\Models\ProductSpec;
  4. use Illuminate\Support\Collection;
  5. use Illuminate\Support\Facades\DB;
  6. use Maatwebsite\Excel\Concerns\ToCollection;
  7. class ProductSpecImport implements ToCollection
  8. {
  9. private int $product_id;
  10. private array $keys;
  11. public function __construct(int $product_id)
  12. {
  13. $this->product_id = $product_id;
  14. }
  15. public function collection(Collection $collection)
  16. {
  17. if ($collection->isEmpty()) {
  18. return;
  19. }
  20. //校验数组count()是否正确
  21. if (count($collection[0]) < 6) {
  22. throw new \Exception('Excel产品规格格式不正确');
  23. }
  24. $this->keys = array_flip($collection[0]->toArray());
  25. //去除第一行的标题
  26. unset($collection[0]);
  27. $this->createData($collection);
  28. }
  29. private function createData($rows)
  30. {
  31. $keys = $this->keys;
  32. DB::beginTransaction();
  33. foreach ($rows as $row) {
  34. # Excel日期是从1900-01-01起的天数,PHP日期是1970-01-01起,所以要减去25569天数得到正确日期
  35. $row[$keys['日期']] = date('Y-m-d', strtotime('+ ' . ($row[$keys['日期']] - 25569) . 'day', 0));
  36. ProductSpec::updateOrCreate([
  37. 'product_id' => $this->product_id,
  38. 'name' => $row[$keys['规格名称']],
  39. 'date' => $row[$keys['日期']],
  40. ], [
  41. 'product_id' => $this->product_id,
  42. 'name' => $row[$keys['规格名称']],
  43. 'date' => $row[$keys['日期']],
  44. 'stock' => $row[$keys['库存']],
  45. 'original_price' => $row[$keys['市场价']],
  46. 'price' => $row[$keys['销售价']],
  47. 'cost_price' => $row[$keys['成本价']],
  48. ]);
  49. }
  50. DB::commit();
  51. }
  52. }