【问题标题】:Laravel - Saving metadata to many to many relationshipLaravel - 将元数据保存到多对多关系
【发布时间】:2014-05-31 16:13:10
【问题描述】:

我想保存这样的食谱:

                $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”和“名称”创建成分(在成分表中)并将元数据添加到数据透视表(单位和数量)?

谢谢!

【问题讨论】:

    标签: php laravel laravel-4 save relationship


    【解决方案1】:

    知道了!

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

    【讨论】:

      猜你喜欢
      • 2014-05-20
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 2018-07-11
      • 2015-03-05
      • 2014-09-02
      • 1970-01-01
      • 2017-07-17
      相关资源
      最近更新 更多