From 4027bb3631c9c7090123bf898cb18038ed554514 Mon Sep 17 00:00:00 2001 From: Edward Yang Date: Mon, 15 Aug 2022 13:00:14 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BA=A7=E5=93=81=E5=90=8D?= =?UTF-8?q?=E7=A7=B0=E8=AF=BB=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- beike/Repositories/ProductRepo.php | 46 +++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/beike/Repositories/ProductRepo.php b/beike/Repositories/ProductRepo.php index 8593e11e..41e95de2 100644 --- a/beike/Repositories/ProductRepo.php +++ b/beike/Repositories/ProductRepo.php @@ -20,6 +20,9 @@ use Illuminate\Http\Resources\Json\AnonymousResourceCollection; class ProductRepo { + private static $allProductsWithName; + + /** * 获取产品详情 */ @@ -122,7 +125,7 @@ class ProductRepo } - public static function list($data=[]) + public static function list($data = []) { return self::getBuilder($data)->paginate($data['per_page'] ?? 20); } @@ -146,14 +149,14 @@ class ProductRepo } /** - * 获取商品名称 + * 获取商品ID获取单个商品名称 + * * @param $id * @return HigherOrderBuilderProxy|mixed|string */ - public static function getName($id) + public static function getNameById($id) { $product = Product::query()->find($id); - if ($product) { return $product->description->name; } @@ -161,6 +164,41 @@ class ProductRepo } + /** + * 通过产品ID获取商品名称 + * @param $id + * @return mixed|string + */ + public static function getName($id) + { + $categories = self::getAllProductsWithName(); + return $categories[$id]['name'] ?? ''; + } + + + /** + * 获取所有商品ID和名称列表 + * + * @return array|null + */ + public static function getAllProductsWithName(): ?array + { + if (self::$allProductsWithName !== null) { + return self::$allProductsWithName; + } + + $items = []; + $products = self::getBuilder()->select('id')->get(); + foreach ($products as $product) { + $items[$product->id] = [ + 'id' => $product->id, + 'name' => $product->description->name ?? '', + ]; + } + return self::$allProductsWithName = $items; + } + + /** * @param $productIds * @return array