You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel9+PHP8.1中使用maatwebsite/excel导入后如何获取带ID的保存数据

实现获取导入后带自增ID的记录

方案一:修改导入类,手动保存并收集记录

适合单条插入场景,直接在导入过程中收集保存后的模型实例:

  1. 更新导入类
    在BankTransfersHistoryImport中添加存储记录的属性,修改model方法手动保存并收集实例:
class BankTransfersHistoryImport implements ToModel, WithHeadingRow, WithValidation
{
    use Importable;

    // 存储已保存的模型实例
    public array $savedRecords = [];

    public function model(array $row)
    {
        $record = new BankTransfersHistory([    
            'loanId' => $row['loanId'],
            'actionDate' => transformDate($row['actionDate']),
            'worth' => $row['worth'],
            // 补充其他字段
        ]);

        // 手动保存模型,此时实例会包含自增ID
        $record->save();
        $this->savedRecords[] = $record;

        return $record;
    }

    // 保留原有的headingRow和rules方法
    public function headingRow(): int
    {
        return 2;
    }

    public function rules(): array
    {
        return [ 
            '*.loanId' => ['required', 'numeric'],
            // 你的其他验证规则
        ];
    }
}
  1. 在控制器中获取记录
    执行导入后,直接通过导入类的$savedRecords属性获取带ID的记录:
$import = new BankTransfersHistoryImport;

try {
    // 日期验证逻辑
    $collection = $import->toCollection($file);
    // ... 你的日期验证代码 ...

    // 执行导入
    $import->import($file);

    // 将模型实例转换为数组格式
    $savedData = array_map(fn($record) => $record->toArray(), $import->savedRecords);

    // 后续可通过ID执行更新操作
    // ... 你的更新逻辑 ...

    return [
        "message" => "导入完成",
        "data" => $savedData,
    ];

} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
    $failures = $e->failures();
    $errors = [];
    foreach ($failures as $failure) {
        $errors[] = [
            'row' => $failure->row(),
            'field' => $failure->attribute(),
            'messages' => $failure->errors(),
            'values' => $failure->values()
        ];
    }
    return $errors;
}

方案二:批量插入后通过匹配条件查询ID(适合批量场景)

如果导入使用WithBatchInserts优化性能,单条保存方式不适用,可在导入完成后根据loanId和actionDate查询数据库获取对应ID:

$import->import($file);

// 从导入的集合中提取匹配条件
$matchConditions = $collection->first()->map(fn($row) => [
    'loanId' => $row['loanId'],
    'actionDate' => transformDate($row['actionDate'])
])->toArray();

// 查询获取带ID的记录
$savedData = BankTransfersHistory::whereIn(
    ['loanId', 'actionDate'],
    $matchConditions
)->get()->toArray();

注意事项

  • 确保BankTransfersHistory模型中设置了正确的$fillable属性,允许批量赋值字段。
  • 若使用方案二,需确保loanId + actionDate组合在数据库中是唯一的,避免查询到重复记录。

内容的提问来源于stack exchange,提问作者yakov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 09:45:37