Laravel CSV导入时11E2被转为1100存入MySQL varchar列求助
解决Laravel CSV导入时"11E2"被转为1100的问题
这个问题是因为PHP或CSV导入工具(比如Maatwebsite/Laravel-Excel)自动将类似科学计数法格式的字符串识别为数字,即便dump时显示正常,入库前还是会被转换。以下是几种强制以字符串形式导入的方法:
方法1:在导入类的模型映射中强制转字符串
假设你使用的是Maatwebsite/Laravel-Excel的ToModel实现,直接在model方法中将目标字段强制转为字符串:
namespace App\Imports; use App\Models\Student; use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Concerns\WithHeadingRow; class StudentsImport implements ToModel, WithHeadingRow { public function model(array $row) { // 强制将目标字段(比如code)转为字符串,若有包裹引号则先去除 $code = is_string($row['code']) ? trim($row['code'], '"') : (string)$row['code']; return new Student([ 'code' => $code, // 其他字段映射... ]); } }
方法2:针对特定列配置单元格值处理
如果需要精准控制某一列的读取格式,可实现WithCellValueCalculation接口,强制指定列返回字符串:
namespace App\Imports; use App\Models\Student; use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Concerns\WithHeadingRow; use Maatwebsite\Excel\Concerns\WithCellValueCalculation; class StudentsImport implements ToModel, WithHeadingRow, WithCellValueCalculation { public function calculateCellValue($value, $column, $row) { // 替换成你的目标列名,比如code if ($column === 'code') { return (string)$value; } return $value; } public function model(array $row) { return new Student([ 'code' => $row['code'], // 其他字段映射... ]); } }
方法3:检查并修正模型字段转换配置
确保你的Student模型没有将目标字段(如code)设置为数字类型的$casts,否则即便导入时是字符串,模型保存时仍会自动转换:
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Student extends Model { protected $casts = [ // 移除或注释掉类似如下的数字类型转换配置 // 'code' => 'integer', // 'code' => 'float', ]; }
方法4:原生CSV读取时的处理(若未用Laravel Excel)
如果是用PHP原生fgetcsv读取CSV,直接在读取后强制转字符串:
$csvFile = fopen(storage_path('app/students.csv'), 'r'); // 跳过表头 fgetcsv($csvFile); while (($row = fgetcsv($csvFile, 0, ',', '"')) !== false) { // 假设目标值在第三列(索引2) $code = (string)$row[2]; // 存入数据库 Student::create([ 'code' => $code, // 其他字段... ]); } fclose($csvFile);
额外注意事项
- 确认MySQL中对应字段类型为
varchar(而非int/float),且长度足够容纳目标字符串; - 若CSV中该字段有引号包裹,确保读取时正确解析(比如Laravel Excel的
getCsvSettings中设置'enclosure' => '"')。
内容的提问来源于stack exchange,提问作者user3274489
相关产品推荐
相关产品推荐

