导入操作
简介
Filament 引入了一个可以从 CSV 导入行数据的 Action。点击触发按钮后,模态框向用户请求文件。文件上传后,可以将 CSV 中的每一列映射到数据库的列字段中。如果有任何一行验证失败,这些行数据将会在其他行导入后,被编译到一个可下载的 CSV 中,供用户进行查阅。用户也可以下载包含可被导入的所有列信息的 CSV 示例文件。
该特性使用了队列批量操作及数据库通知,因此你需要发布这些迁移到 Laravel 中。同时,也需要发布 Filament 用于存储导入数据的迁移表:
php artisan make:queue-batches-table
php artisan make:notifications-table
php artisan vendor:publish --tag=filament-actions-migrations
php artisan migrate
如果你想在面板中接收导入通知,可以在面板配置中启用。
NOTE
如果你使用的是 PostgreSQL,请确保通知迁移中的 data 字段使用 json(): $table->json('data')。
NOTE
如果 User 模型使用了 UUID,请确保通知迁移的 notifiable 字段使用 uuidMorphs(): $table->uuidMorphs('notifiable')
ImportAction 可以像这样使用:
use App\Filament\Imports\ProductImporter;
use Filament\Actions\ImportAction;
ImportAction::make()
->importer(ProductImporter::class)

如果你想将该 Action 添加到表头,可以这样使用:
use App\Filament\Imports\ProductImporter;
use Filament\Actions\ImportAction;
use Filament\Tables\Table;
public function table(Table $table): Table
{
return $table
->headerActions([
ImportAction::make()
->importer(ProductImporter::class)
]);
}
需要创建 "importer" 类,以告知 Filament 如何导入 CSV 的每一行。
如果在同一个地方有多个 ImportAction,你需要在 make() 方法中为每个 Action 都指定一个唯一的名称:
use Filament\Actions\ImportAction;
ImportAction::make('importProducts')
->importer(ProductImporter::class)
ImportAction::make('importBrands')
->importer(BrandImporter::class)
创建导入器
要为模型创建 importer 类,可以使用 make:filament-importer 命令,并传入模型名称:
php artisan make:filament-importer Product
该命令将在 app/Filament/Imports 目录下创建一个新类。你需要定义可被导入的列字段。
自动生成导入器字段
如果你想节省时间,可以使用 --generate,将Filament 基于模型的数据库字段,为你自动生成列字段:
php artisan make:filament-importer Product --generate
