BatchMigrateToModelAction.php 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. <?php
  2. namespace App\Module\Cleanup\AdminControllers\Actions;
  3. use App\Module\Cleanup\Models\CleanupPlanContent;
  4. use App\Module\Cleanup\Models\CleanupConfig;
  5. use Dcat\Admin\Grid\BatchAction;
  6. use Dcat\Admin\Actions\Response;
  7. use Illuminate\Http\Request;
  8. /**
  9. * 批量迁移到Model类Action
  10. *
  11. * 批量将使用表名的旧数据迁移为使用Model类
  12. */
  13. class BatchMigrateToModelAction extends BatchAction
  14. {
  15. /**
  16. * 按钮标题
  17. */
  18. protected $title = '批量迁移到Model';
  19. /**
  20. * 处理请求
  21. */
  22. public function handle(Request $request)
  23. {
  24. $ids = $this->getKey();
  25. if (empty($ids)) {
  26. return $this->response()->error('请选择要迁移的记录');
  27. }
  28. $successCount = 0;
  29. $failedCount = 0;
  30. $errors = [];
  31. foreach ($ids as $id) {
  32. try {
  33. $content = CleanupPlanContent::findOrFail($id);
  34. // 跳过已经使用Model类的记录
  35. if (!empty($content->model_class)) {
  36. continue;
  37. }
  38. // 检查是否有表名
  39. if (empty($content->table_name)) {
  40. $errors[] = "ID {$id}: 没有表名";
  41. $failedCount++;
  42. continue;
  43. }
  44. // 查找对应的Model类
  45. $config = CleanupConfig::where('table_name', $content->table_name)
  46. ->whereNotNull('model_class')
  47. ->where('model_class', '!=', '')
  48. ->first();
  49. if (!$config) {
  50. $errors[] = "ID {$id}: 未找到表 {$content->table_name} 对应的Model类";
  51. $failedCount++;
  52. continue;
  53. }
  54. // 验证Model类是否存在
  55. if (!class_exists($config->model_class)) {
  56. $errors[] = "ID {$id}: Model类不存在 {$config->model_class}";
  57. $failedCount++;
  58. continue;
  59. }
  60. // 更新为使用Model类
  61. $content->update([
  62. 'model_class' => $config->model_class,
  63. ]);
  64. $successCount++;
  65. } catch (\Exception $e) {
  66. $errors[] = "ID {$id}: " . $e->getMessage();
  67. $failedCount++;
  68. }
  69. }
  70. // 构建结果消息
  71. $message = "迁移完成!成功: {$successCount} 个,失败: {$failedCount} 个";
  72. if (!empty($errors)) {
  73. $message .= "\n\n失败详情:\n" . implode("\n", array_slice($errors, 0, 10));
  74. if (count($errors) > 10) {
  75. $message .= "\n... 还有 " . (count($errors) - 10) . " 个错误";
  76. }
  77. }
  78. if ($failedCount > 0) {
  79. return $this->response()
  80. ->warning($message)
  81. ->refresh();
  82. } else {
  83. return $this->response()
  84. ->success($message)
  85. ->refresh();
  86. }
  87. }
  88. /**
  89. * 确认对话框
  90. */
  91. public function confirm()
  92. {
  93. return [
  94. '确认批量迁移到Model类?',
  95. '此操作将查找对应的Model类并批量更新配置,建议在迁移前备份数据。'
  96. ];
  97. }
  98. /**
  99. * 权限检查
  100. */
  101. public function allowed()
  102. {
  103. return true;
  104. }
  105. }