From 06eb3d0a7595051fe9d77f9b5c99af81c976a6a7 Mon Sep 17 00:00:00 2001 From: Stephen Cameron Date: Mon, 9 Sep 2019 10:26:48 +0200 Subject: [PATCH] Prevent extra queries when fetching cart data. WIP #2738 @0.25 --- app/Models/Product.php | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/app/Models/Product.php b/app/Models/Product.php index 86ae446..ebf261d 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -14,7 +14,7 @@ class Product extends CubistMagicPageModel protected static $_specifications = null; protected static $_productTypes = null; protected static $_specificationFields = null; - protected static $_cart_data; + protected static $_cart_data = null; /** * @var array @@ -353,20 +353,23 @@ class Product extends CubistMagicPageModel if (!self::$_cart_data) { $cart_items = session('cart_items', []); - self::$_cart_data = []; - $products = self::with('media')->whereIn('id', array_keys($cart_items))->get(); - - foreach ($products as $product) { - self::$_cart_data[] = [ - 'id' => $product->id, - 'name' => $product->name, - 'reference' => $product->reference, - 'category' => $product->type->name, - 'quantity' => $cart_items[$product->id], - 'image' => $product->image, - 'URL' => $product->url, - ]; + + if (count($cart_items) > 0) { + + $products = self::with('media')->whereIn('id', array_keys($cart_items))->get(); + + foreach ($products as $product) { + self::$_cart_data[] = [ + 'id' => $product->id, + 'name' => $product->name, + 'reference' => $product->reference, + 'category' => $product->type->name, + 'quantity' => $cart_items[$product->id], + 'image' => $product->image, + 'URL' => $product->url, + ]; + } } } -- 2.39.5