Php Can';无法从Laravel中的透视表获取所有数据
我正在尝试使用数据透视表,但无法获得所需的所有数据。 我有三个DB表:Php Can';无法从Laravel中的透视表获取所有数据,php,laravel,Php,Laravel,我正在尝试使用数据透视表,但无法获得所需的所有数据。 我有三个DB表: 1.ingredients 2.recipes 3.ingredients_in_recipe (Pivot table) 1.成分表包含两种成分: -------------------- -- id | name -- -- 1 | Potatoes -- -- 2 | Onions -- -------------------- 2.配方表包含三种配方: -------------------
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.配方表中的配料:
---------------------------------------
-- id | recipe_id| ingredient_id --
-- 1 | 1 | 1 --
-- 2 | 2 | 2 --
-- 3 | 3 | 1 --
-- 4 | 3 | 2 --
---------------------------------------
成分模型:
公共函数配方(){
返回$this->belongtomany('App\Recipe','component\u Recipe');
}
配料控制器:
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);
}
公共函数读取(请求$Request)
{
//我们搜索一个或多个id的配料(1=土豆,2=洋葱)
$配料=配料::findOrFail([1,2]);
$recipes=[];
foreach($成分作为$成分){
$recipes=$Component->recipes()->get();
}
返回视图('home')->带有('recipes',$recipes);
}
视图:
@foreach($recipes作为$recipe)
{{$recipe->name}
@endforeach
我希望从查询中得到所有的菜谱,但实际上我只得到了两个菜谱(带洋葱的菜谱(id:2)和带土豆和洋葱的菜谱(id:3)
我缺少什么?试试下面的内容
配料控制器:
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);
}
在控制器中,以下行导致了问题:
$recipes=$component->recipes()->get();
这只是保存最后一种配料的配方
我建议您将read
方法的内容替换为以下内容:
$components=配料::with('recipes')->findOrFail([1,2]);
$recipes=收集([]);
foreach($成分作为$成分){
$recipes=$recipes->merge($component->recipes);
}
返回视图('home')->带有('recipes',$recipes);
如果您能解释OP的错误以及修复原因,而不是仅仅删除一块代码,那将非常有帮助。