49 lines
1.2 KiB
PHP
49 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Imports;
|
|
|
|
use App\Models\Artist;
|
|
use App\Enums\ArtistCategory;
|
|
use Maatwebsite\Excel\Concerns\ToModel;
|
|
use Maatwebsite\Excel\Concerns\WithHeadingRow;
|
|
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
|
|
|
|
class ArtistDataImport implements ToModel, WithHeadingRow
|
|
{
|
|
public int $successCount = 0;
|
|
public int $failCount = 0;
|
|
|
|
public function __construct()
|
|
{
|
|
// 關閉 heading row 格式化
|
|
HeadingRowFormatter::default('none');
|
|
}
|
|
|
|
public function model(array $row)
|
|
{
|
|
$name = trim($row['名稱'] ?? '');
|
|
$category = trim($row['類別'] ?? '未定義');
|
|
$enable = trim($row['狀態'] ?? 1);
|
|
if (empty($name)) {
|
|
$this->failCount++;
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
Artist::firstOrCreate(
|
|
['name' => $name],
|
|
['category' => ArtistCategory::tryFrom($category) ?? ArtistCategory::Unset],
|
|
['enable' => $enable],
|
|
);
|
|
$this->successCount++;
|
|
} catch (\Throwable $e) {
|
|
$this->failCount++;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
public function headingRow(): int
|
|
{
|
|
return 1;
|
|
}
|
|
} |