2017-10-22 141 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(); 
相关问题