CleanupLog.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <?php
  2. namespace App\Module\Cleanup\Models;
  3. use App\Module\Cleanup\Enums\CLEANUP_TYPE;
  4. use UCore\ModelCore;
  5. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  6. /**
  7. * 清理日志模型
  8. *
  9. * 记录每个表的清理操作详情
  10. * field start
  11. * @property int $id 主键ID
  12. * @property int $task_id 任务ID
  13. * @property string $table_name 表名
  14. * @property string $model_class Model类名
  15. * @property int $cleanup_type 清理类型:1清空表,2删除所有,3按时间删除,4按用户删除,5按条件删除
  16. * @property int $before_count 清理前记录数
  17. * @property int $after_count 清理后记录数
  18. * @property int $deleted_records 删除记录数
  19. * @property float $execution_time 执行时间(秒)
  20. * @property array $conditions 使用的清理条件
  21. * @property string $error_message 错误信息
  22. * @property \Carbon\Carbon $created_at 创建时间
  23. * field end
  24. *
  25. */
  26. class CleanupLog extends ModelCore
  27. {
  28. /**
  29. * 数据表名
  30. */
  31. protected $table = 'cleanup_logs';
  32. // attrlist start
  33. protected $fillable = [
  34. 'id',
  35. 'task_id',
  36. 'table_name',
  37. 'model_class',
  38. 'cleanup_type',
  39. 'before_count',
  40. 'after_count',
  41. 'deleted_records',
  42. 'execution_time',
  43. 'conditions',
  44. 'error_message',
  45. ];
  46. // attrlist end
  47. /**
  48. * 字段类型转换
  49. */
  50. protected $casts = [
  51. 'task_id' => 'integer',
  52. 'cleanup_type' => 'integer',
  53. 'before_count' => 'integer',
  54. 'after_count' => 'integer',
  55. 'deleted_records' => 'integer',
  56. 'execution_time' => 'float',
  57. 'conditions' => 'array',
  58. 'created_at' => 'datetime',
  59. 'updated_at' => 'datetime',
  60. ];
  61. /**
  62. * 获取清理类型枚举
  63. */
  64. public function getCleanupTypeEnumAttribute(): CLEANUP_TYPE
  65. {
  66. return CLEANUP_TYPE::from($this->cleanup_type);
  67. }
  68. /**
  69. * 关联任务
  70. */
  71. public function task(): BelongsTo
  72. {
  73. return $this->belongsTo(CleanupTask::class, 'task_id');
  74. }
  75. /**
  76. * 获取成功的日志
  77. */
  78. public function scopeSuccessful($query)
  79. {
  80. return $query->whereNull('error_message');
  81. }
  82. /**
  83. * 获取失败的日志
  84. */
  85. public function scopeFailed($query)
  86. {
  87. return $query->whereNotNull('error_message');
  88. }
  89. /**
  90. * 按表名筛选
  91. */
  92. public function scopeByTable($query, string $tableName)
  93. {
  94. return $query->where('table_name', $tableName);
  95. }
  96. /**
  97. * 按清理类型筛选
  98. */
  99. public function scopeByCleanupType($query, CLEANUP_TYPE $cleanupType)
  100. {
  101. return $query->where('cleanup_type', $cleanupType->value);
  102. }
  103. }