2016-09-16 77 views
0

我正在使用Laravel 5.3
如何更新Laravel中的相關表格?如何更新Laravel中的相關表格?

有2個表,studentshobbies,它們有多對多的關係。

在視圖中,愛好是複選框,這樣的:

<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 

在控制器,store()方法是這樣的,它可以工作:

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

你不應該使用更新。使用sync方法:

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

'$學生 - >愛好() - >連接($請求 - >愛好);'應該是'$學生 - >愛好() - >同步($請求 - >愛好);'?但它也行不通。 – zwl1619

+0

它不會更新或引發錯誤? –

+0

它的工作原理,謝謝! – zwl1619