Laravel 8插入books表数据报SQLSTATE[HY000] 1364错误的解决求助
Laravel 8 图书新增功能插入报错排查
触发的原始报错:
SQLSTATE[HY000]: General error: 1364 Field 'sudents_id' doesn't have a default value (SQL: insert into \books` (`bookname`, `auther`, `cost`, `book_image`, `updated_at`, `created_at`) values (Maths, Ali, 1000, 1613387802.png, 2021-02-15 11:16:43, 2021-02-15 11:16:43))`
现有代码片段
控制器存储方法
public function create() { return view('books.create'); } public function store(Request $request) { $request->validate([ 'bookname' => 'required', 'auther' => 'required', 'cost' => 'required', 'students_Id'=>'nullable', 'book_image'=> 'required ', ]); $image=$request->file('book_image'); $ext=$image->extension(); $file=time().'.'.$ext; $image->storeAs('public/image',$file); $data=array( 'bookname'=>$request->input('bookname'), 'auther'=>$request->input('auther'), 'cost'=>$request->input('cost'), 'students_Id'=>$request->input('students_Id'), 'book_image'=>$file, ); Book::create($data); return redirect()->route('books.index') ->with('success','Book added successfully.'); }
数据表迁移定义
public function up() { Schema::create('books', function (Blueprint $table) { $table->id(); $table->string('bookname'); $table->string('auther'); $table->string('cost'); $table->binary('book_image'); $table->timestamps(); // 注释掉的旧外键定义 /* $table->bigIncrements('std_id'); $table->foreign('std_id') ->references('id') ->on('students') ->onDelete('cascade'); */ $table->foreignId('sudents_id')->constrained('students'); }); }
报错根因
- 字段名拼写不匹配:迁移定义的数据库字段是
sudents_id(本身存在拼写错误,缺字母t),控制器传参用的键名是students_Id,两者无法匹配,导致最终生成的插入SQL完全没有带上这个字段 - 数据库字段无空值兼容:
foreignId默认生成的是NOT NULL属性的外键,且无默认值,当插入SQL缺失该字段时,数据库直接抛出1364错误 - 批量赋值限制:未确认Book模型的
$fillable属性是否包含对应字段名,就算参数名匹配,也可能被Laravel的批量赋值保护机制过滤掉,导致插入语句缺失字段
修复步骤
- 统一全链路字段命名:
- 修正迁移里的字段拼写错误,将
sudents_id改为规范的student_id,和控制器传参键名保持完全一致 - 给可空的外键增加
nullable()修饰,修改迁移定义为$table->foreignId('student_id')->nullable()->constrained('students'),从数据库层面允许该字段存储空值 - 若旧表已经存在,不要直接回滚删除迁移,新建独立迁移修改现有表的字段属性,避免影响已有业务数据
- 修正迁移里的字段拼写错误,将
- 对齐控制器传参:将
$data数组里的students_Id键名改为和数据库字段完全一致的名称,确保参数能正确映射到插入语句 - 配置模型批量赋值规则:在Book模型中,将
student_id加入$fillable数组,解除Laravel对该字段的批量赋值限制
内容的提问来源于stack exchange,提问作者FaSiH Ur ReHmAn
相关产品推荐
相关产品推荐

