ImportSpecificCategories.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Console\Commands;
  3. use Carbon\Carbon;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\Log;
  7. /*
  8. * 导入产品分类
  9. * 运行命令:php artisan import:specific-categories
  10. */
  11. class ImportSpecificCategories extends Command
  12. {
  13. /**
  14. * The name and signature of the console command.
  15. *
  16. * @var string
  17. */
  18. protected $signature = 'import:specific-categories';
  19. /**
  20. * The console command description.
  21. *
  22. * @var string
  23. */
  24. protected $description = 'Command description';
  25. /**
  26. * Execute the console command.
  27. *
  28. * @return int
  29. */
  30. public function handle()
  31. {
  32. // 获取主类记录
  33. $mainCategories = DB::table('album_path')
  34. ->whereIn('name', ['功能类产品', '屏幕保护膜', '智能切膜机'])
  35. ->where('parent_id', 0)
  36. ->get();
  37. // 获取所有需要导入的类的ID
  38. $idsToImport = [];
  39. foreach ($mainCategories as $main) {
  40. $idsToImport[] = $main->id;
  41. $this->getSubCategories($main->id, $idsToImport);
  42. }
  43. // 获取所有需要导入的类
  44. $categoriesToImport = DB::table('album_path')
  45. ->whereIn('id', $idsToImport)
  46. ->get();
  47. // 插入到目标表并记录ID映射
  48. $idMapping = [];
  49. $tableMapping = [];
  50. foreach ($categoriesToImport as $category) {
  51. $parentId = $category->parent_id == 0 ? 0 : ($idMapping[$category->parent_id] ?? 0);
  52. $newId = DB::table('base_product_category')->insertGetId([
  53. 'name' => $category->name,
  54. 'parent_id' => $parentId,
  55. 'order' => 0,
  56. 'enabled' => 1,
  57. 'created_at' => Carbon::now(),
  58. 'updated_at' => Carbon::now(),
  59. ]);
  60. $idMapping[$category->id] = $newId;
  61. $tableMapping[] = ['base_product_category'=>$newId, 'album_path_id'=>$category->id];
  62. }
  63. // 记录映射关系
  64. Log::info('tableMapping: '.json_encode($tableMapping));
  65. $this->info('Categories imported successfully!');
  66. }
  67. // 递归获取所有子类ID
  68. private function getSubCategories($parentId, &$ids)
  69. {
  70. $subCategories = DB::table('album_path')
  71. ->where('parent_id', $parentId)
  72. ->get();
  73. foreach ($subCategories as $sub) {
  74. $ids[] = $sub->id;
  75. $this->getSubCategories($sub->id, $ids);
  76. }
  77. }
  78. }