2016-09-16 22 views
0

私はLaravel 5.3を使用しています。
Laravelで関連テーブルを更新するにはどうすればよいですか?Laravelで関連するテーブルを更新するには?

studentshobbiesの2つのテーブルがあり、多対多リレーションシップを持っています。鑑み

、趣味は、このようなチェックボックスである:store()方法は次のようである、それが動作することができ、コントローラは

<input class="form-check-input" type="checkbox" name="hobby[]" value="1" > basketball 
<input class="form-check-input" type="checkbox" name="hobby[]" value="2" > football 
<input class="form-check-input" type="checkbox" name="hobby[]" value="3" > swimming 

public function store(Request $request) 
{ 
    $student=Student::create($request->except('hobby')); 
    $student->hobbies()->attach($request->hobby); 
    return redirect()->action('[email protected]'); 
} 

update()方法は趣味ができない、このようなものです更新する:

public function update(Request $request, $id) 
{ 
    $student = Student::findOrFail($id); 
    $student->update($request->except('hobby')); 

    //How to update hobbies? 
    $student->hobbies()->attach($request->hobby); 

    return redirect()->action('[email protected]', ['id' => $id]); 
} 

趣味を更新するには?

答えて

3

更新プログラムを使用しないでください。 - ; `べきである` $スチューデント>趣味() - >同期($要求 - >趣味>($要求 - >趣味)を取り付け

$student->hobbies()->sync($request->hobby); 
+0

'$スチューデント>趣味():syncメソッドを使用します。 ); '?しかしそれはまた働かない。 – zwl1619

+0

エラーをスローしたりスローしたりしませんか? –

+0

それは、ありがとう! – zwl1619

関連する問題