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.
|
|
<?php
namespace App\Imports;
use App\Models\ProductSpec;use Illuminate\Support\Collection;use Illuminate\Support\Facades\DB;use Maatwebsite\Excel\Concerns\ToCollection;
class ProductSpecImport implements ToCollection{ private int $product_id; private array $keys;
public function __construct(int $product_id) { $this->product_id = $product_id; }
public function collection(Collection $collection) { if ($collection->isEmpty()) { return; }
//校验数组count()是否正确
if (count($collection[0]) < 6) { throw new \Exception('Excel产品规格格式不正确'); }
$this->keys = array_flip($collection[0]->toArray());
//去除第一行的标题
unset($collection[0]);
$this->createData($collection); }
private function createData($rows) { $keys = $this->keys; DB::beginTransaction(); foreach ($rows as $row) { # Excel日期是从1900-01-01起的天数,PHP日期是1970-01-01起,所以要减去25569天数得到正确日期
$time = strtotime($row[$keys['日期']]); if ($time === false) { $row[$keys['日期']] = date('Y-m-d', strtotime('+ ' . ($row[$keys['日期']] - 25569) . 'day', 0)); } else { $row[$keys['日期']] = date('Y-m-d', $time); }
ProductSpec::updateOrCreate([ 'product_id' => $this->product_id, 'name' => $row[$keys['规格名称']], 'date' => $row[$keys['日期']], ], [ 'product_id' => $this->product_id, 'name' => $row[$keys['规格名称']], 'date' => $row[$keys['日期']], 'stock' => $row[$keys['库存']], 'original_price' => $row[$keys['市场价']], 'price' => $row[$keys['销售价']], 'cost_price' => $row[$keys['成本价']], ]); } DB::commit(); }}
|