插入新记录(如果不存在)并更新(如果存在),laravel 5.4

时间:2017-10-22 04:42:25

标签: php laravel-5

如果不存在,是否有任何方法可以插入新记录,如果存在则更新记录?以下是我使用的代码。

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 但我希望一个学生ID可能有很多课程代码,但不能重复。所以我想检查学生是否有相同的课程或课程,然后跳过或更新它并插入新的记录。 请帮我。 感谢。

3 个答案:

答案 0 :(得分:1)

检查id是否存在然后更新,否则插入

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

答案 1 :(得分:1)

例如,如果您有一个表格供每个用户投票一次或更新他的投票;

//give the record to use

    $record = request('vote');
    //checkif there is a record for user in model
    $row = Uservoting::where('user_id',Auth->user()->id)->first;
    //if true
    if($row!==null){
        //update
        $row::update(['vote' => $record]);
        //if there isn't in model
    }else{
        //create a new row and insert the value
        $new_row = new Uservoting();
        $new_row->user_id = Auth->user()->id ;
        $new_row->vote = $record ;
        $new_row->vote();`

    }

希望这项工作:) {{--如果您发现任何错误,请告诉我--}}

答案 2 :(得分:0)

使用firstOrCreate / firstOrNew

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