rows !== null) { return $this->rows; } $rows = [self::HEADERS]; if ($this->template) { $rows[] = ['西红柿', '蔬菜/茄果类', '示例供应商', '新发地', '10斤/箱', '斤', 2.5, 0, 100, 3, '上架', '示例行,导入前请删除']; return $this->rows = collect($rows); } $products = ProductModel::query() ->when($this->categoryId > 0, fn ($query) => $query->where('category_id', $this->categoryId)) ->orderBy('sort') ->orderBy('id') ->get() ->makeVisible('cost_price'); $categoryPaths = $this->categoryPaths($products->pluck('category_id')->unique()->all()); $supplierNames = SupplierModel::withTrashed()->pluck('name', 'id'); foreach ($products as $product) { $rows[] = [ $product->name, $categoryPaths[(int) $product->category_id] ?? '', $supplierNames[(int) $product->supplier_id] ?? '', $product->market, $product->spec, $product->unit, (float) $product->cost_price, (int) $product->sort, (int) $product->stock, (int) $product->shelf_life, (int) $product->status === ProductModel::STATUS_ON ? '上架' : '下架', $product->remark, ]; } return $this->rows = collect($rows); } /** * 列头加粗、冻结首行、设置列宽 */ public function styles(Worksheet $sheet): array { $this->collection(); $sheet->freezePane('A2'); $widths = [20, 16, 14, 12, 14, 8, 10, 8, 8, 8, 8, 24]; foreach ($widths as $index => $width) { $sheet->getColumnDimension(Coordinate::stringFromColumnIndex($index + 1))->setWidth($width); } return [ 1 => ['font' => ['bold' => true]], ]; } /** * 分类ID => 「父分类/子分类」完整路径(沿 parent_id 上溯拼接) * * @param array $categoryIds * @return array */ private function categoryPaths(array $categoryIds): array { $categories = ProductCategoryModel::all()->keyBy('id'); $paths = []; foreach ($categoryIds as $categoryId) { $names = []; $cursor = (int) $categoryId; $guard = 0; while ($cursor > 0 && $guard++ < 20) { $category = $categories->get($cursor); if ($category === null) { break; } array_unshift($names, $category->name); $cursor = (int) $category->parent_id; } $paths[(int) $categoryId] = implode('/', $names); } return $paths; } }