2017-05-26 162 views
0

我有兩個表第一個是科目表第二個是subjects_doctors表。這裏的關係是一對多Laravel更新一對多關係

更新方法的代碼:

public function update(Request $request, $id) 
    { 
     $this -> validate($request, [ 
      'name'   => 'required', 
      'max_students' => 'required', 
      'doctors'  => 'required', 
      'description' => 'required' 
     ]); 

     $subject = Subject::find($id); 
     $subject -> name   = $request -> name; 
     $subject -> description  = $request -> description; 
     $subject -> max_students = $request -> max_students; 
     $subject -> save(); 
//PROBLEM 
     $y = Subject::where('id', $subject -> id) -> doctors() -> update(['doctor_id' => $request -> doctors]); 


     Session::flash('success', 'Subject has been updated successfully!'); 
     return redirect() -> route('subjects.index'); 
    } 

$request的變量包含具有所有更新的醫生ID陣列。

對於實例

我在科目表subject 1 HAVE 1 DOCTOR而且我已經更新到SUBJECT 1 HAVE 2 DOCTORS ..我怎麼做呢?

我有一切變數,但我無法在subjects_doctors表中更新它們。

回答

0

該問題已通過使用Laravel的sync()函數解決。謝謝。

這裏是代碼,它可以幫助

$subject = Subject::find($id); 
    $subject -> name   = $request -> name; 
    $subject -> description  = $request -> description; 
    $subject -> max_students = $request -> max_students; 
    $subject -> save(); 

    $subject -> doctors() -> sync($request -> doctors);