Laravel中JSON字段无法接收其他列值,如何修改表单实现数据收集?
问题解决步骤
1. 先修复数据库字段的默认值错误
你遇到的SQLSTATE[HY000]: General error: 1364 Field 'properties' doesn't have a default value错误,是因为数据库里的properties字段没设默认值,且创建记录时没给这个字段传值。
修改迁移文件(如果是已运行过的迁移,建议新建迁移修改字段),给properties添加默认空JSON:
// 原迁移文件修改properties字段定义 $table->json('properties')->default(json_encode([]));
如果是已执行的迁移,新建一个字段修改迁移:
public function up() { Schema::table('hunters', function (Blueprint $table) { $table->json('properties')->default(json_encode([]))->change(); }); }
执行迁移命令让修改生效:
php artisan migrate
2. 实现properties收集其他列数据的逻辑
你的表单不需要修改现有输入控件,要收集的是已经提交的字段值,只需要在后端处理请求数据:
修改HunterController.php的store方法:
public function store(HunterRequest $request) { $validations = $request->validated(); // 定义要存入properties的目标字段列表 $targetFields = [ 'name_hunter', 'year_hunter', 'height_hunter', 'weight_hunter', 'type_hunter', 'type_nen', 'type_sangue' ]; // 筛选出目标字段的值,存入properties $validations['properties'] = array_intersect_key($validations, array_flip($targetFields)); HunterModel::create($validations); return redirect('/'); }
3. 配置模型批量赋值权限
在HunterModel.php里把properties加入$fillable,允许批量赋值操作:
protected $fillable = [ 'name_hunter', 'year_hunter', 'height_hunter', 'weight_hunter', 'type_hunter', 'type_nen', 'type_sangue', 'properties' ];
表单说明
你当前的表单已经能正确提交所有需要的字段,不需要做任何输入控件的修改。如果后续要动态添加额外字段到properties,可以在表单里添加隐藏字段或动态生成的输入框,但当前需求下现有表单完全够用。
内容的提问来源于stack exchange,提问作者user20509677
相关产品推荐
相关产品推荐

