#php #laravel
#php #ларавель
Вопрос:
Я пытаюсь работать со сводной таблицей, но не могу получить все данные, которые мне нужны. У меня есть три таблицы БД:
1.ingredients
2.recipes
3.ingredients_in_recipe (Pivot table)
1. Таблица ингредиентов содержит два ингредиента:
--------------------
-- id | name --
-- 1 | Potatoes --
-- 2 | Onions --
--------------------
2. Таблица рецептов содержит три рецепта:
---------------------------------------------
-- id | name --
-- 1 | Recipe with potatoes --
-- 2 | Recipe with onions --
-- 3 | Recipe with potatoes and onions --
---------------
3.Таблица ingredients_in_recipe:
---------------------------------------
-- id | recipe_id| ingredient_id --
-- 1 | 1 | 1 --
-- 2 | 2 | 2 --
-- 3 | 3 | 1 --
-- 4 | 3 | 2 --
---------------------------------------
Модель ингредиента:
public function recipes() {
return $this->belongsToMany('AppRecipe', 'ingredient_recipe');
}
Контроллер ингредиентов:
public function read(Request $request)
{
//we search one or more id of ingredients (1=Potatoes, 2=Onions)
$ingredients = Ingredient::findOrFail([1,2]);
$recipes = [];
foreach($ingredients as $ingredient) {
$recipes = $ingredient->recipes()->get();
}
return view('home')->with('recipes', $recipes);
}
Вид:
@foreach ($recipes as $recipe)
{{$recipe->name}}
@endforeach
Я ожидал получить все рецепты из запроса, но на самом деле я получаю только два рецепта (рецепт с луком (id: 2) и рецепт с картофелем и луком (id: 3).
Чего мне не хватает?
Ответ №1:
В вашем контроллере следующая строка вызывает проблему:
$recipes = $ingredient->recipes()->get();
Это сохранение рецептов только для последнего ингредиента.
Я предлагаю вам заменить содержимое вашего read
метода it на это:
$ingredients = Ingredient::with('recipes')->findOrFail([1,2]);
$recipes = collect([]);
foreach($ingredients as $ingredient) {
$recipes = $recipes->merge($ingredient->recipes);
}
return view('home')->with('recipes', $recipes);
Ответ №2:
попробуйте ниже.
Контроллер ингредиентов:
public function read(Request $request)
{
$ingredients = Ingredient::with('recipes')->findOrFail([1,2]);
$recipes = [];
foreach($ingredients as $ingredient) {
$recipes[] = $ingredient->recipes;
}
return view('home')->with('recipes', $recipes);
}
Комментарии:
1. Было бы полезно, если бы вы объяснили, что OP сделал неправильно и почему это исправляет, вместо того, чтобы просто отбрасывать блок кода.