Laravel外键'student_id'没有默认值,即使它在请求中

时间:2018-08-29 10:57:42

标签: laravel default-value insert-update

迁移:

Schema::create('students_detail', function (Blueprint $table) {
           $table->increments('id');
           $table->unsignedInteger('student_id');
           $table->integer('lessons')->nullable();
           $table->string('tests',200)->nullable();

           $table->timestamps();

           $table->foreign('student_id')->references('id')->on('students')

       });

控制器

public function update(Request $request, StudentsDetail $studentsDetail)
   {
       $student_id= $request->input('student_id');
       $studentsDetail->update($request->except('student_id'));
       $studentsDetail->save();


       return redirect()->back();
   }

我尝试将mysql strict设置为false,但不能解决我的错误,注意:我不能使列'student_id'为空,因为它是外键,所以在更新此错误时会出现吗?我不知道如何摆脱它!

2 个答案:

答案 0 :(得分:1)

在模型文件保护的$ fillable数组中添加student_id,例如:

 protected $fillable = ['student_id'];

在控制器上保存代码:

$attributes = $request->all(); // print_r($request->all()) this request and check have you got student_id fields?
$studentsDetail->update($attributes);
return redirect()->back();

答案 1 :(得分:0)

您必须将其传递给更新方法:

public function update(Request $request, StudentsDetail $studentsDetail)
{
    $studentsDetail->update($request->all());
    $studentsDetail->save();


    return redirect()->back();
}