如何使用 laravel 导入将数据保存到数据库?

How to save data to db using laravel import?

我准备了下面的代码,我正在使用 dump 来跟踪它是否传递给了模型的 create 函数。

当我检查数据库时没有添加数据,我只是想知道为什么它已经传入 User::create 函数却没有(通过下面图片中的字符串“created”验证).


这些是返回的转储数据(注意:我使用图片是为了更好地可视化)


这是我在 UserImport.php

中的代码
public function model(array $row)
{
    User::create([
        'name' => $row[0],
        'birthdate' => $row[1],
        'gender' => $row[2],
    ]);

    dump('created');
}

public function rules(): array
{
    return [
        '1' => ['required'],
        '2' => ['required'],
    ];
}

关于转储验证消息是我的 UserController (为了缩短,我只 post 重要部分)

catch (\Maatwebsite\Excel\Validators\ValidationException $e)
{
    $failures = $e->failures();
    dd($failures);
}

这是预期的行为。 Laravel Excel 使用数据库事务来确保执行导入时的数据完整性。你有失败,所以整个事务被回滚。

https://docs.laravel-excel.com/3.1/imports/validation.html#database-transactions

#Database transactions
The entire import is automatically wrapped in a database transaction, that means that every error will rollback the entire import. When using batch inserts, only the current batch will be rollbacked.