繁体   English   中英

无法从Laravel中的数据透视表获取所有数据

[英]Can't get all data from Pivot Table in Laravel

我正在尝试使用数据透视表,但无法获取所需的所有数据。 我有三个数据库表:

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('App\Recipe', '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)。

我缺少什么?

在您的控制器中,以下行引起了该问题:

$recipes = $ingredient->recipes()->get();

它只是保存最后一种食材的配方。

我建议您用此方法替换您的read方法的内容:

$ingredients = Ingredient::with('recipes')->findOrFail([1,2]);
$recipes = collect([]);
foreach($ingredients as $ingredient) {
    $recipes = $recipes->merge($ingredient->recipes);
}
return view('home')->with('recipes', $recipes);

请尝试以下。

成分控制器:

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM