我正在尝试将员工编号保存为EMP00001格式。我在存储区下的控制器中使用了以下代码,并且遇到了非数值错误。
$emp = Employee::create($request->all()+
['employee_number' => Employee::max('employee_number') + 1 ]);
$employee_code = sprintf ("EMP",'%06d');
$employee_no = ($employee_code +$emp);
$employee_no->save();
employee_number的MySQL列为varchar。谁能看到我在做什么错?
答案 0 :(得分:2)
由于Employee::max('employee_number')
返回一个字符串,因此它是varchar列类型,因为您以EMP00001
的格式插入它们,所以会引发此类错误。
您已经为PHP设置了严格类型,这很好。
尝试在主查询之外调用它,提取数字,向其添加数字并执行插入操作:
$num_employee_max = Employee::max('employee_number');
$num_employee = (int)str_replace('EMP', '', $num_employee_max);
$new_num_employee = $num_employee + 1;
$employee_code = sprintf('EMP%06d',$new_num_employee);
$sanitized values = $request->all(); //do the proper sanitization instead of this
$emp = Employee::create( $sanitized values +
['employee_number' => $employee_code]);
注意:避免直接从数据库中的输入中插入未经处理的值。
此外,sprintf(“ EMP”,'%06d');什么都没做 查看有关sprintf的信息:http://php.net/manual/en/function.sprintf.php
答案 1 :(得分:1)
尝试
$emp = Employee::create(array_collapse([
$request->toArray(),
['employee_number' => preg_replace("|(\d+)|e",
"$1+1",Employee::max('employee_number'))]
]));
$employee_code = sprintf ("EMP",'%06d');
$employee_no = ($employee_code +$emp);
$employee_no->save();