如何在Laravel 中将数据插入到多对多的表中

两个表:学生,课程。尝试添加新学生并将学生分配到已经存在的许多课程时,使用Laravel.
在学生模型中

    public function courses()
    {
        return $this->belongsToMany('App\Course');
    }

在课程模型中我添加

   public function student()
{
    return $this->belongsToMany('App\Student');
}

在studentController中

public function store(Request $request,Courses courses){
    $student = Student::createStudent($request->all());
    $courses = Course::find($request->get('courses'));
    $student->courses()->attach($courses);
    return redirect('/admin/student')->with('success','Has been added'); 
}

在学生create.blade中

  <select name='courses[]' style="width:220px;" multiple="multiple">
          @foreach( $courses as $course )
                   <option value="{{$course->id}}">{{$course->name_courses}}</option>
           @endforeach
</select>
阅读 267

Comments