我目前正在使用Laravel Excel包开发Excel导入功能。我正在实现OnEachRow
、WithHeadingRow
、WithValidation
、SkipsEmptyRows
、SkipsOnFailure
、SkipsOnError
和WithEvents
接口。
我的类使用prepareForValidation
方法在验证数据之前准备和操作数据。但是,在导入过程中,似乎每一行都会调用prepareForValidation
两次。这导致了意想不到的结果。
下面是我使用prepareForValidation
的课堂摘录:
public function prepareForValidation($data, $index)
{
dump($index, $data); // debug
$rules = $this->rules();
foreach ($data as $key => $value) {
if (empty($rules[$key]))
continue;
if (in_array('date', $rules[$key])) {
$data[$key] = Date::excelToDateTimeObject($value);
}
if (in_array('boolean', $rules[$key])) {
$data[$key] = human2Bool($value);
}
}
unset($data['']);
dump($data); //debug
return $data;
}
如您所见,在prepareForValidation
方法中,我将Excel日期转换为DateTime对象,并将一些布尔值从人类可读格式转换为布尔格式。但是,在初始数据转换之后,似乎会使用相同的行数据再次调用该函数。奇怪的是,如果我删除Date::excelToDateTimeObject
转换,这种行为不会发生...
第一个prepareForValidation
调用:
"row index:" 3
"data at the beginning of the function:"
array:8 [
"name" => "Test one"
"uuid" => "656e9c21-b77a-4a9a-ba3d-e2490effcadd"
"" => 1
"execution_structure_id" => "fc1fbdf8-ea73-4d0a-a9a5-f1530a3d49b8"
"is_locked" => "n"
"end_at" => 45056
"duration" => null
"methodological_status" => null
]
"data at the end of the function:"
array:7 [
"name" => "Test one"
"uuid" => "656e9c21-b77a-4a9a-ba3d-e2490effcadd"
"execution_structure_id" => "fc1fbdf8-ea73-4d0a-a9a5-f1530a3d49b8"
"is_locked" => false
"end_at" => "2023-05-10"
"duration" => null
"methodological_status" => null
]
第二次prepareForValidation
调用:
"row index:" 3
"data at the beginning of the function:"
array:8 [
"name" => "Test one"
"uuid" => "656e9c21-b77a-4a9a-ba3d-e2490effcadd"
"" => "1"
"execution_structure_id" => "fc1fbdf8-ea73-4d0a-a9a5-f1530a3d49b8"
"is_locked" => "n"
"end_at" => "45056"
"duration" => null
"methodological_status" => null
]
"data at the end of the function:"
array:7 [
"name" => "Test one"
"uuid" => "656e9c21-b77a-4a9a-ba3d-e2490effcadd"
"execution_structure_id" => "fc1fbdf8-ea73-4d0a-a9a5-f1530a3d49b8"
"is_locked" => false
"end_at" => "2023-05-10"
"duration" => null
"methodological_status" => null
]
如上所述,在第一次调用prepareForValidation
时,“end_at”字段是一个整数(Excel的数字日期格式)。转换后,它会变成一个DateTime对象(“2023-05-10”)。但是,在第二次调用prepareForValidation
时,'end_at'字段再次恢复为字符串(“45056”)。
我尝试将“end_at”验证规则更改为date_format:Y-m-d
,但问题仍然存在。
以前有人经历过吗?有没有什么解释可以解释为什么prepareForValidation
每行会被调用两次,以及如何防止这种情况发生?
我使用的是Laravel Excel版本3.1
。
任何帮助将不胜感激。
1条答案
按热度按时间kx5bkwkv1#
好的我知道了在我的
public function onRow(Row $row)
中,我使用$row->toCollection()
和$row->toArray()
。这些正在重新触发验证过程,并且prepareForValidation
也再次被调用...