[英]Laravel - Saving metadata to many to many 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和名稱”的“成分”(在成分表中)並將元數據添加到數據透視表(單位和數量)?
謝謝!
得到它了!
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()丟失了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.