MigrateToModelAction.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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\RowAction;
  6. use Dcat\Admin\Actions\Response;
  7. use Illuminate\Http\Request;
  8. /**
  9. * 迁移到Model类Action
  10. *
  11. * 将使用表名的旧数据迁移为使用Model类
  12. */
  13. class MigrateToModelAction extends RowAction
  14. {
  15. /**
  16. * 按钮标题
  17. */
  18. protected $title = '迁移到Model';
  19. /**
  20. * 按钮图标
  21. */
  22. protected $icon = 'fa-arrow-up';
  23. /**
  24. * 处理请求
  25. */
  26. public function handle(Request $request)
  27. {
  28. $contentId = $this->getKey();
  29. try {
  30. $content = CleanupPlanContent::findOrFail($contentId);
  31. // 检查是否已经使用Model类
  32. if (!empty($content->model_class)) {
  33. return $this->response()
  34. ->error('此记录已经使用Model类,无需迁移');
  35. }
  36. // 检查是否有表名
  37. if (empty($content->table_name)) {
  38. return $this->response()
  39. ->error('此记录没有表名,无法迁移');
  40. }
  41. // 查找对应的Model类
  42. $config = CleanupConfig::where('table_name', $content->table_name)
  43. ->whereNotNull('model_class')
  44. ->where('model_class', '!=', '')
  45. ->first();
  46. if (!$config) {
  47. return $this->response()
  48. ->error('未找到表 ' . $content->table_name . ' 对应的Model类配置');
  49. }
  50. // 验证Model类是否存在
  51. if (!class_exists($config->model_class)) {
  52. return $this->response()
  53. ->error('Model类不存在:' . $config->model_class);
  54. }
  55. // 更新为使用Model类
  56. $content->update([
  57. 'model_class' => $config->model_class,
  58. ]);
  59. return $this->response()
  60. ->success('迁移成功!已更新为使用Model类:' . class_basename($config->model_class))
  61. ->refresh();
  62. } catch (\Exception $e) {
  63. return $this->response()
  64. ->error('迁移失败:' . $e->getMessage());
  65. }
  66. }
  67. /**
  68. * 确认对话框
  69. */
  70. public function confirm()
  71. {
  72. return [
  73. '确认迁移到Model类?',
  74. '此操作将查找对应的Model类并更新配置,建议在迁移前备份数据。'
  75. ];
  76. }
  77. /**
  78. * 权限检查
  79. */
  80. public function allowed()
  81. {
  82. // 只对没有Model类的记录显示此按钮
  83. $content = $this->row;
  84. return empty($content->model_class);
  85. }
  86. /**
  87. * 按钮样式
  88. */
  89. public function html()
  90. {
  91. return '<a class="btn btn-sm btn-warning ' . $this->getElementClass() . '" title="' . $this->title . '">
  92. <i class="' . $this->icon . '"></i> ' . $this->title . '
  93. </a>';
  94. }
  95. }