CleanupLog.php 2.8 KB

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