0
我正在使用Laravel 5.3
。
如何更新Laravel中的相關表格?如何更新Laravel中的相關表格?
有2個表,students
和hobbies
,它們有多對多的關係。
在視圖中,愛好是複選框,這樣的:
<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]);
}
如何更新業餘愛好?
'$學生 - >愛好() - >連接($請求 - >愛好);'應該是'$學生 - >愛好() - >同步($請求 - >愛好);'?但它也行不通。 – zwl1619
它不會更新或引發錯誤? –
它的工作原理,謝謝! – zwl1619