CleanupLog.php 2.4 KB

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