2017-10-22 137 views
1

如果不存在,是否有任何方法插入新記錄並更新記錄(如果存在)?以下是我使用的代碼。如果不存在,插入新記錄並更新(如果存在),laravel 5.4

public function store(Request $request) 
{ 
    $inputs = $request->all(); 
    $this->validate($request,[ 
      'course_code'=>'required' 
     ]); 
    $batch = $request->batch; 
    $students = User::select('student_id')->where('batch', $batch)->get(); 

    $course_codes = $inputs['course_code']; 
    $data=[]; 
    foreach ($students as $student) { 
     foreach ($course_codes as $course_code) { 
     $data[]=[ 
      'batch' => $batch, 
      'student_id' => $student->student_id, 
      'semester' => $inputs['semester'], 
      'course_code' => $course_code, 
      "created_at" => \Carbon\Carbon::now(), # \Datetime() 
      "updated_at" => \Carbon\Carbon::now() # \Datetime() 
      ]; 
     } 
    }  

    DB::table('assign_batches')->insert($data); 
    return redirect('/admin/assign/batch/create')->with('message', 'A batch has been assigned to courses successfully!'); 
} 

這是我的輸出,當我再次插入相同的記錄。 enter image description here 但我想要一個學生證可能有很多課程代碼,但不能重複。所以我想檢查學生是否有相同的課程或課程,然後跳過或更新它並插入新的記錄。 請幫幫我。 謝謝。

+0

您還可以使用SQL查詢: $ SQL =「INSERT INTO {$ _table}({$ _columns })VALUES {$ _values}在DUPLICATE KEY UPDATE {$ updates}「; DB :: statement($ sql); – Shan

回答

1

檢查id如果存在,則更新,否則插入

if(isset($request->id)){ 
    DB::table('assign_batches')->where("id", $request->id)->update($data); 
}else { 
    DB::table('assign_batches')->insert($data); 
} 
+0

感謝您的回答。其實我想檢查是否有兩個記錄(student_id和course_code)存在或不在表格行中。你能澄清一下嗎? –

+0

需要一個'id'的隱藏輸入,它在laravel模板視圖中是唯一的,並且作爲給出的答案檢查 – C2486

+0

我認爲不需要''isDuplicate = DB :: table('assign_batches' ) - > where('student_id',$ student-> student_id) - > where('course_code',$ course_code) - > count()'然後檢查'$ isDuplicate> 0'是否更新,否則插入。 – C2486

0

使用firstOrCreate/firstOrNew

$students = User::firstOrNew(['student_id' => $request->student_id, 'course_code' => $request->course_code]); 
$students->foo = $request->foo; 
$students->save(); 
相關問題