现在我正在开发一个Web应用程序,它可以通过选择从mysql检索到的多种食物并输入其数量来制作食谱 . 我的用户界面是这样的;

Html

<form action="{{ URL::route('store') }}" method="post">
    Your recipe name: <input type="text" name="recipe_name">

      <!-- Generating multiple rows with jquery-->
      '<tr>
        <td>' + add_food + '<input name="food[]" hidden="true" value="'+ add_food +'"></td>
        <td><input name="amount[]" class="amount" type="number"/></td>
      </tr>'

    <input type="submit" value="Make a recipe!">
</form>

Models and relation

我已经设置了两个名为 DishFood 的表,它具有多对多关系,这些表由名为 dish_food 的数据透视表中介 .

What I want to do

我想创造一种名为'Pizza'的新食谱,其中包括80克面包,20克奶酪和10克香肠 . 因此,在我的UI中,我选择这三种食物并输入其数量,然后提交这些数据 . 最后我要像这样插入 dish_idfood_idamount ;

dish_id| food_id|  amount
-------|--------|--------
     1 |      1 |     80 
     1 |      2 |     20
     1 |      3 |     10

Controller I am struggling now

public function store()
{
    // Here comes some validation...

    // Getting data from UI.

        $name     = Input::get('name');
        $foods    = Input::get('foods');  // $foods is storing multiple data.
        $amounts = Input::get('amount'); // $amounts is storing multiple data.

    // Store recipe name into Dish table.
        $dish = Dish::create([
            'name'  => $name
        ]);

    // Here is my problem.
        $food_ids = Food::where('name', '=', $foods)->get(['id']);

        foreach($food_ids as $position => $food_id){

            $dish->foods()->attach($food_id, array_get($amounts, $position));

        return Redirect::route('create-recipe')
                ->with('global', 'You have made one recipe!');
}

Problem

使用上面的代码,我可以像这样在 Dish 表中插入一个新的食谱名称;

dish_id|  name
-------|--------
     1 |  pizza

But 我无法在我的数据透视表 dish_food 中插入多个数据,我无法收到任何错误消息!所以我需要你的帮助 . 如何修复我的代码?

我已经检查了这样的相关问题;

Laravel attach pivot to table with multiple values