AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RelatedProducts.php 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Storefront;
  3. use App\Models\BundleItem;
  4. use App\Models\Product;
  5. use Illuminate\Database\Eloquent\Builder;
  6. use Illuminate\Database\Eloquent\Collection;
  7. /**
  8. * "Pairs well with" on a product page.
  9. *
  10. * Products that are sold together in a bundle come first (they really do go together), then the bundles
  11. * this product is part of, then other products shoppers can buy now, newest first.
  12. */
  13. final class RelatedProducts
  14. {
  15. public const int LIMIT = 4;
  16. /**
  17. * @return Collection<int, Product>
  18. */
  19. public static function for(Product $product): Collection
  20. {
  21. $bundleIds = BundleItem::query()->where('product_id', $product->id)->pluck('bundle_id')->all();
  22. // Other products inside the same bundles, then the bundles themselves.
  23. $partners = BundleItem::query()->whereIn('bundle_id', $bundleIds)->pluck('product_id')->all();
  24. $wanted = array_values(array_unique(array_merge($partners, $bundleIds)));
  25. $picked = self::query($product)->whereKey($wanted)->get()
  26. ->sortBy(fn (Product $candidate) => array_search($candidate->id, $wanted, true))
  27. ->values();
  28. if ($picked->count() < self::LIMIT) {
  29. $more = self::query($product)
  30. ->whereKeyNot($picked->modelKeys())
  31. ->where('stock', '>', 0)
  32. ->latest('id')
  33. ->limit(self::LIMIT - $picked->count())
  34. ->get();
  35. $picked = $picked->concat($more);
  36. }
  37. return $picked->take(self::LIMIT)->values();
  38. }
  39. /**
  40. * @return Builder<Product>
  41. */
  42. private static function query(Product $product): Builder
  43. {
  44. return Product::query()
  45. ->where('store_id', $product->store_id)
  46. ->active()
  47. ->whereKeyNot($product->id)
  48. ->with(Product::STOREFRONT_RELATIONS);
  49. }
  50. }