简体   繁体   中英

How to update one to many relationship in laravel?

I have a problem with updating the following table

在此处输入图像描述

And the data come from the view like below

在此处输入图像描述this is my code

 foreach ($request->input('class_teacher') as $key=>$value){
                $class_teacher =ClassTeacher::where('class_id',$id);
                $class_teacher->class_id = $classes->class_id;
                $class_teacher->teacher_id =$value;
                $class_teacher->save();
            }

after the update I want it to be like this one

在此处输入图像描述

First delete the relationships, then recreate them all again.

 ClassTeacher::where('class_id',$id)->whereIn('teacher_id', $request->input('class_teacher'))->delete();
  
  foreach ($request->input('class_teacher') as $key=>$value){
    $class_teacher =new ClassTeacher;
    $class_teacher->class_id = $classes->class_id;
    $class_teacher->teacher_id =$value;
    $class_teacher->save();
  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM