Laravel;如何使用多对多关系将多个ID和值附加到数据透视表?

时间:2015-04-16 14:29:57

标签: laravel many-to-many pivot

现在我正在开发一个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>

模型和关系

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

我想做什么

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

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

控制器我现在正在努力

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

问题

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

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

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

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

Laravel attach pivot to table with multiple values

1 个答案:

答案 0 :(得分:0)

也许在这一行中您只会得到一个ID

 $food_ids = Food::where('name', '=', $foods)->get(['id']);

尝试将其更改为

$food_ids = Food::whereIn('name', $foods)->get(['id']);