Php Laravel-将元数据保存到多对多关系
我想保存这样一个食谱:Php Laravel-将元数据保存到多对多关系,php,laravel,laravel-4,save,relationship,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('sho
$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);
我通过邮递员输入的数据:因此,我的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()不见了
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']]);
}