80 lines
2.4 KiB
PHP
80 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace Database\Seeders;
|
|
|
|
use App\Models\Ecommerce\Product\Category\Category;
|
|
use File;
|
|
use Illuminate\Database\Seeder;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class CategoryTableSeeder extends Seeder
|
|
{
|
|
/**
|
|
* Run the database seeds.
|
|
*/
|
|
public function run(): void
|
|
{
|
|
$this->seedOldData();
|
|
}
|
|
|
|
/**
|
|
* Seed old postshop data
|
|
*/
|
|
public function seedOldData(): void
|
|
{
|
|
Category::truncate();
|
|
|
|
$datas = collect(json_decode(File::get('database/data/categories.json')));
|
|
|
|
// Insert root categories
|
|
$rootCategories = $datas->whereNull('parent_id');
|
|
$rootCategories->each(function ($data) {
|
|
$this->insertCategory($data);
|
|
});
|
|
|
|
// Insert child categories
|
|
$childCategories = $datas->whereNotNull('parent_id');
|
|
$restOfCategories = collect();
|
|
$childCategories->each(function ($data) use ($rootCategories, $restOfCategories) {
|
|
if ($rootCategories->pluck('id')->contains($data->parent_id)) {
|
|
$this->insertCategory($data);
|
|
} else {
|
|
$restOfCategories->push($data);
|
|
}
|
|
});
|
|
|
|
$restOfCategories->each(function ($data) use ($rootCategories, $childCategories) {
|
|
if ($rootCategories->pluck('id')->contains($data->parent_id) || $childCategories->pluck('id')->contains($data->parent_id)) {
|
|
$this->insertCategory($data);
|
|
} else {
|
|
info('Skipping category: '.$data->name);
|
|
}
|
|
});
|
|
|
|
$table = 'categories';
|
|
DB::statement("
|
|
SELECT setval('{$table}_id_seq', (SELECT MAX(id) from {$table}))
|
|
");
|
|
}
|
|
|
|
// Encapsulate the category insertion logic in a separate function
|
|
public function insertCategory($data)
|
|
{
|
|
DB::table('categories')->insert([
|
|
'id' => $data->id,
|
|
'parent_id' => $data->parent_id,
|
|
'name' => $data->name,
|
|
'slug' => $data->slug,
|
|
'type' => $data->type,
|
|
'description' => $data->description,
|
|
'seo_title' => $data->seo_title,
|
|
'seo_description' => $data->seo_description,
|
|
'is_visible' => $data->is_enabled,
|
|
'tax_percentage' => $data->tax_percentage,
|
|
'options' => sprintf('{"color":"%s"}', $data->color),
|
|
'created_at' => $data->created_at,
|
|
'updated_at' => $data->updated_at,
|
|
]);
|
|
}
|
|
}
|