ImportSpecificCategories.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. exit;
  33. // 获取主类记录
  34. $mainCategories = DB::table('album_path')
  35. ->whereIn('name', ['功能类产品', '屏幕保护膜', '智能切膜机'])
  36. ->where('parent_id', 0)
  37. ->get();
  38. // 获取所有需要导入的类的ID
  39. $idsToImport = [];
  40. foreach ($mainCategories as $main) {
  41. $idsToImport[] = $main->id;
  42. $this->getSubCategories($main->id, $idsToImport);
  43. }
  44. // 获取所有需要导入的类
  45. $categoriesToImport = DB::table('album_path')
  46. ->whereIn('id', $idsToImport)
  47. ->get();
  48. // 插入到目标表并记录ID映射
  49. $idMapping = [];
  50. $tableMapping = [];
  51. foreach ($categoriesToImport as $category) {
  52. $parentId = $category->parent_id == 0 ? 0 : ($idMapping[$category->parent_id] ?? 0);
  53. $newId = DB::table('base_product_category')->insertGetId([
  54. 'name' => $category->name,
  55. 'parent_id' => $parentId,
  56. 'order' => 0,
  57. 'enabled' => 1,
  58. 'created_at' => Carbon::now(),
  59. 'updated_at' => Carbon::now(),
  60. ]);
  61. $idMapping[$category->id] = $newId;
  62. $tableMapping[] = ['base_product_category'=>$newId, 'album_path_id'=>$category->id];
  63. }
  64. // 记录映射关系
  65. Log::info('tableMapping: '.json_encode($tableMapping));
  66. $this->info('Categories imported successfully!');
  67. }
  68. // 递归获取所有子类ID
  69. private function getSubCategories($parentId, &$ids)
  70. {
  71. $subCategories = DB::table('album_path')
  72. ->where('parent_id', $parentId)
  73. ->get();
  74. foreach ($subCategories as $sub) {
  75. $ids[] = $sub->id;
  76. $this->getSubCategories($sub->id, $ids);
  77. }
  78. }
  79. }