I'm trying to work with a pivot table but I can't get all the data that I need. I have three DB tables:
1.ingredients
2.recipes
3.ingredients_in_recipe (Pivot table)
1.The ingredients table contains two ingredients:
--------------------
-- id | name --
-- 1 | Potatoes --
-- 2 | Onions --
--------------------
2.The recipes table contains three recipes:
---------------------------------------------
-- id | name --
-- 1 | Recipe with potatoes --
-- 2 | Recipe with onions --
-- 3 | Recipe with potatoes and onions --
---------------
3.The ingredients_in_recipe table:
---------------------------------------
-- id | recipe_id| ingredient_id --
-- 1 | 1 | 1 --
-- 2 | 2 | 2 --
-- 3 | 3 | 1 --
-- 4 | 3 | 2 --
---------------------------------------
Ingredient Model:
public function recipes() {
return $this->belongsToMany('App\Recipe', 'ingredient_recipe');
}
Ingredient Controller:
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);
}
View:
@foreach ($recipes as $recipe)
{{$recipe->name}}
@endforeach
I expected to get all the recipes from the query but actually I get only two recipes (recipe with onions (id:2) and recipe with potatoes and onions (id:3).
What I am missing?
In your controller, the following line is causing the problem:
$recipes = $ingredient->recipes()->get();
It is only saving the recipes for the last ingredient.
I suggest you replace the contents of your read
method it with this one:
$ingredients = Ingredient::with('recipes')->findOrFail([1,2]);
$recipes = collect([]);
foreach($ingredients as $ingredient) {
$recipes = $recipes->merge($ingredient->recipes);
}
return view('home')->with('recipes', $recipes);
try below.
Ingredient Controller:
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.