简体   繁体   English

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

[英]Laravel - Saving metadata to many to many relationship

I want to save a recipe like this: 我要保存这样的食谱:

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

Data I input via POSTMAN: 我通过POSTMAN输入的数据:
http://monosnap.com/image/K5e44iPt3SRaeNhxZqwduXBfIyOeD9 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))  

So it seems that my foreach doesn't create the "ingredients", it just wants to add them. 因此,我的foreach似乎没有创建“成分”,它只是想添加它们。

How can I create the Ingredient(in the ingredients table) with "ID and "name" and add the meta data to the pivot table (unit and amount) ? 如何创建带有“ ID和名称”的“成分”(在成分表中)并将元数据添加到数据透视表(单位和数量)?

Thanks! 谢谢!

Got it! 得到它了!

             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() was missing! -> save()丢失了!

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

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