Laravel8+Angular12级联下拉未选state_id报SQL整数错误如何解决
错误根因
你遇到的SQL报错是因为MySQL的int类型字段state_id/city_id被存入了空字符串''或者字符串类型的'null',数值类型字段不允许存储非数字格式的空值,只接受合法整数或者NULL(前提是字段设置了允许为NULL)。
解决方案
1. 后端Laravel侧修改(优先改,兜底兼容所有前端传值情况)
第一步:调整数据表字段属性
先确认employees表的state_id、city_id字段已经设置为nullable,如果没有可以修改迁移文件执行更新,或者直接在数据库中将字段改为允许NULL,默认值设为NULL。
第二步:修改数据保存逻辑
将原来的空字符串兜底改为NULL兜底,同时对传入的数值做强制类型转换:
$employee = Employee::find($id); $employee->nationality_id = $request->nationality_id; // filled方法判断参数存在且不为空/空字符串/NULL,符合要求就转成整数,否则存NULL $employee->state_id = $request->filled('state_id') ? (int) $request->state_id : null; $employee->city_id = $request->filled('city_id') ? (int) $request->city_id : null; $employee->save();
如果业务不允许字段为NULL,可以将null改为0作为未选中的默认值。
2. 前端Angular侧修改(优化传值逻辑,避免无效参数提交)
第一步:修改表单初始化默认值
将省、市控件的默认值从空字符串改为null:
updateEmployee() { this.profileInfoForm = this.fb.group({ nationality_id: ['', [Validators.required]], state_id: [null], city_id: [null], }); }
第二步:调整联动清空逻辑
切换国籍/省份时,直接清空对应表单控件的值,同时清空下级下拉选项:
loadCountryData(event: any) { // 清空省、市表单值 this.profileInfoForm.patchValue({ state_id: null, city_id: null }); this.cstates = []; this.cities = []; if (event) { this.country_id = event.id; this.cstatesService.getStatesByCountry(this.country_id).subscribe( (data) => { this.cstates = data.results.states; } ); } else { this.country_id = ''; } } loadStateData(event: any) { // 清空市表单值 this.profileInfoForm.patchValue({ city_id: null }); this.cities = []; if (event) { this.state_id = event.id; this.citiesService.fetchCitiesByState(this.state_id).subscribe( (data) => { this.cities = data.results.cities; } ); } else { this.state_id = ''; } }
第三步:表单提交时过滤空值
提交前判断省、市是否有值,空值无需拼接到FormData中:
const formProfileData = this.profileInfoForm.getRawValue(); const formData = new FormData(); formData.append('nationality_id', formProfileData.nationality_id); if (formProfileData.state_id) { formData.append('state_id', formProfileData.state_id.toString()); } if (formProfileData.city_id) { formData.append('city_id', formProfileData.city_id.toString()); }
内容的提问来源于stack exchange,提问作者mikefolu
相关产品推荐
相关产品推荐

