93 lines
2.7 KiB
PHP
93 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace Database\Seeders;
|
|
|
|
use App\Models\Category;
|
|
use Illuminate\Database\Seeder;
|
|
|
|
class CategorySeeder extends Seeder
|
|
{
|
|
public function run(): void
|
|
{
|
|
$csvPath = collect([
|
|
storage_path('app/dataset_final.csv'),
|
|
database_path('dataset_final.csv'),
|
|
database_path('dataset_final.xls'),
|
|
storage_path('app/dataset_mobil.csv'),
|
|
])->first(fn ($path) => file_exists($path));
|
|
|
|
if (! $csvPath) {
|
|
$this->command->warn('File CSV dataset mobil tidak ditemukan.');
|
|
return;
|
|
}
|
|
|
|
$this->command->info("Menggunakan dataset: {$csvPath}");
|
|
|
|
$file = fopen($csvPath, 'r');
|
|
fgetcsv($file);
|
|
|
|
$count = 0;
|
|
$batchSize = 50;
|
|
|
|
while (($data = fgetcsv($file)) !== false) {
|
|
if (count($data) < 8) {
|
|
continue;
|
|
}
|
|
|
|
$count++;
|
|
$this->insertCategory($data);
|
|
|
|
if ($count % $batchSize === 0) {
|
|
$this->command->info("Batch processed: {$count} records...");
|
|
}
|
|
}
|
|
|
|
fclose($file);
|
|
|
|
$this->command->info("Successfully imported {$count} vehicles.");
|
|
}
|
|
|
|
private function insertCategory(array $data): void
|
|
{
|
|
$merk = trim($data[0] ?? '');
|
|
$model = trim($data[1] ?? '');
|
|
$kategori = trim($data[2] ?? '');
|
|
$tahun = (int) ($data[3] ?? 2023);
|
|
$mesinCc = (int) ($data[4] ?? 0);
|
|
$transmisi = trim($data[5] ?? '');
|
|
$bahanBakar = trim($data[6] ?? '');
|
|
$harga = (float) ($data[7] ?? 0);
|
|
if ($merk === '' || $model === '' || $harga <= 0) {
|
|
return;
|
|
}
|
|
|
|
$name = "{$merk} {$model}";
|
|
$description = "{$kategori} | {$mesinCc}cc | {$transmisi} | {$bahanBakar}";
|
|
|
|
try {
|
|
$category = Category::where('name', $name)
|
|
->where('year', $tahun)
|
|
->where('price', $harga)
|
|
->where('description', $description)
|
|
->first()
|
|
?? new Category();
|
|
|
|
$category->fill([
|
|
'name' => $name,
|
|
'description' => $description,
|
|
'merk' => $merk,
|
|
'model' => $model,
|
|
'kategori' => $kategori,
|
|
'price' => $harga,
|
|
'year' => $tahun,
|
|
'mesin_cc' => $mesinCc,
|
|
'transmisi' => $transmisi,
|
|
'bahan_bakar' => $bahanBakar,
|
|
'status' => $category->exists ? $category->status : 'available',
|
|
])->save();
|
|
} catch (\Exception $exception) {
|
|
$this->command->warn("Error inserting {$name}: {$exception->getMessage()}");
|
|
}
|
|
}
|
|
}
|