Laravel - 将元数据保存为多对多关系

时间:2014-04-16 16:44:24

标签: php laravel laravel-4 save relationship

我想要保存这样的食谱:

                $recipe = new Recipe;
            //$recipe->user_id = Auth::user()->id;
            $recipe->user_id = 40;
            $recipe->title = Input::get('title');
            $recipe->short_desc = Input::get('short_desc');
            $recipe->prep_time = Input::get('prep_time');
            $recipe->status = 0;
            $recipe->amount = Input::get('amount');
            $recipe->save();
            //$recipe->ingredients()->sync(Input::get('ingredients'));
            foreach(Input::get('ingredients') as $key => $ingredient) {
                $recipe->ingredients()->attach($key,['unit' => $ingredient['unit'], 'amount' => $ingredient['amount']]);
            }
            //$recipe->ingredients()->attach($ingredients->id,['unit' => $unit, 'amount' => $amount]);
            $recipe->categories()->sync(Input::get('categories'));
            $recipe->recipesteps()->sync(Input::get('description'));

            $recipe->push();
        //}
        return json_encode($recipe);  

我通过POSTMAN输入的数据:
http://monosnap.com/image/K5e44iPt3SRaeNhxZqwduXBfIyOeD9

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'unit' in 'field list' (SQL: insert into `rezepte_ingredients_recipe` (`amount`, `ingredients_id`, `recipe_id`, `unit`) values (100, 0, 13, gr))  

所以看来我的foreach没有创造“成分”,它只是想添加它们。

如何使用“ID和”名称“创建成分(在成分表中)”并将元数据添加到数据透视表(单位和数量)?

谢谢!

1 个答案:

答案 0 :(得分:0)

知道了!

             foreach(Input::get('ingredients') as $key => $i) {
                $ingredient = new Ingredients(array('name' => $i['name'],'unit' => $i['unit']));
                $ingredient->save();
                $recipe->ingredients()->attach($ingredient->id,['amount' => $i['amount']]);
            }  

- > save()丢失了!