@@ -243,21 +243,25 @@ public function getCocktailsByIngredients(array $ingredientIds, int $barId, ?int
243243 // Basically, goes through all ingredients to match ($ingredientIds) and check if they can create complex ingredients
244244 // If they can, that ingredient is added to the list of ingredients to match
245245 if ($ matchComplexIngredients ) {
246- $ placeholders = str_repeat ('?, ' , count ($ ingredientIds ) - 1 ) . '? ' ;
247- $ rawQuery = "WITH RECURSIVE IngredientChain AS (
248- SELECT id AS matched_ingredient
249- FROM ingredients
250- WHERE id IN ( " . $ placeholders . ")
251- UNION
252- SELECT ci.main_ingredient_id AS matched_ingredient
253- FROM complex_ingredients ci
254- INNER JOIN IngredientChain ic ON ci.ingredient_id = ic.matched_ingredient
255- )
256- SELECT DISTINCT matched_ingredient
257- FROM IngredientChain; " ;
258-
259- $ additionalIngredients = collect ($ this ->db ->select ($ rawQuery , $ ingredientIds ))->pluck ('matched_ingredient ' );
260- $ ingredientIds = array_merge ($ ingredientIds , $ additionalIngredients ->toArray ());
246+ $ additionalIngredients = $ this ->db ->table ('complex_ingredients AS ci ' )
247+ ->distinct ()
248+ ->select ('ci.main_ingredient_id ' )
249+ ->join ('ingredients AS i_main ' , 'ci.main_ingredient_id ' , '= ' , 'i_main.id ' )
250+ ->whereIn ('ci.id ' , function ($ query ) use ($ ingredientIds ) {
251+ $ query ->select ('ci_inner.id ' )
252+ ->from ('complex_ingredients AS ci_inner ' )
253+ ->whereNotExists (function ($ query ) use ($ ingredientIds ) {
254+ $ query ->select ('i_ingredient.id ' )
255+ ->from ('complex_ingredients AS ci_sub ' )
256+ ->join ('ingredients AS i_ingredient ' , 'ci_sub.ingredient_id ' , '= ' , 'i_ingredient.id ' )
257+ ->whereColumn ('ci_sub.main_ingredient_id ' , 'ci_inner.main_ingredient_id ' )
258+ ->whereNotIn ('i_ingredient.id ' , $ ingredientIds );
259+ });
260+ })
261+ ->pluck ('main_ingredient_id ' )
262+ ->toArray ();
263+
264+ $ ingredientIds = array_merge ($ ingredientIds , $ additionalIngredients );
261265 $ ingredientIds = array_unique ($ ingredientIds );
262266 }
263267
0 commit comments