*/ 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 */ private static function query(Product $product): Builder { return Product::query() ->where('store_id', $product->store_id) ->active() ->whereKeyNot($product->id) ->with(Product::STOREFRONT_RELATIONS); } }