| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <?php
-
- namespace App\Storefront;
-
- use App\Models\BundleItem;
- use App\Models\Product;
- use Illuminate\Database\Eloquent\Builder;
- use Illuminate\Database\Eloquent\Collection;
-
- /**
- * "Pairs well with" on a product page.
- *
- * Products that are sold together in a bundle come first (they really do go together), then the bundles
- * this product is part of, then other products shoppers can buy now, newest first.
- */
- final class RelatedProducts
- {
- public const int LIMIT = 4;
-
- /**
- * @return Collection<int, Product>
- */
- public static function for(Product $product): Collection
- {
- $bundleIds = BundleItem::query()->where('product_id', $product->id)->pluck('bundle_id')->all();
-
- // Other products inside the same bundles, then the bundles themselves.
- $partners = BundleItem::query()->whereIn('bundle_id', $bundleIds)->pluck('product_id')->all();
- $wanted = array_values(array_unique(array_merge($partners, $bundleIds)));
-
- $picked = self::query($product)->whereKey($wanted)->get()
- ->sortBy(fn (Product $candidate) => array_search($candidate->id, $wanted, true))
- ->values();
-
- if ($picked->count() < self::LIMIT) {
- $more = self::query($product)
- ->whereKeyNot($picked->modelKeys())
- ->where('stock', '>', 0)
- ->latest('id')
- ->limit(self::LIMIT - $picked->count())
- ->get();
-
- $picked = $picked->concat($more);
- }
-
- return $picked->take(self::LIMIT)->values();
- }
-
- /**
- * @return Builder<Product>
- */
- private static function query(Product $product): Builder
- {
- return Product::query()
- ->where('store_id', $product->store_id)
- ->active()
- ->whereKeyNot($product->id)
- ->with(Product::STOREFRONT_RELATIONS);
- }
- }
|