CleanupBackupFile.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. namespace App\Module\Cleanup\Models;
  3. use App\Module\Cleanup\Enums\BACKUP_TYPE;
  4. use App\Module\Cleanup\Enums\COMPRESSION_TYPE;
  5. use UCore\ModelCore;
  6. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  7. /**
  8. * 清理备份文件模型
  9. *
  10. * 记录备份文件的详细信息
  11. */
  12. class CleanupBackupFile extends ModelCore
  13. {
  14. /**
  15. * 数据表名
  16. */
  17. protected $table = 'cleanup_backup_files';
  18. // field start
  19. /**
  20. * 可批量赋值的字段
  21. */
  22. protected $fillable = [
  23. 'backup_id',
  24. 'table_name',
  25. 'file_name',
  26. 'file_path',
  27. 'file_size',
  28. 'file_hash',
  29. 'backup_type',
  30. 'compression_type',
  31. ];
  32. // field end
  33. /**
  34. * 字段类型转换
  35. */
  36. protected $casts = [
  37. 'backup_id' => 'integer',
  38. 'file_size' => 'integer',
  39. 'backup_type' => 'integer',
  40. 'compression_type' => 'integer',
  41. 'created_at' => 'datetime',
  42. 'updated_at' => 'datetime',
  43. ];
  44. /**
  45. * 获取备份类型枚举
  46. */
  47. public function getBackupTypeEnumAttribute(): BACKUP_TYPE
  48. {
  49. return BACKUP_TYPE::from($this->backup_type);
  50. }
  51. /**
  52. * 获取压缩类型枚举
  53. */
  54. public function getCompressionTypeEnumAttribute(): COMPRESSION_TYPE
  55. {
  56. return COMPRESSION_TYPE::from($this->compression_type);
  57. }
  58. /**
  59. * 关联备份记录
  60. */
  61. public function backup(): BelongsTo
  62. {
  63. return $this->belongsTo(CleanupBackup::class, 'backup_id');
  64. }
  65. /**
  66. * 按表名筛选
  67. */
  68. public function scopeByTable($query, string $tableName)
  69. {
  70. return $query->where('table_name', $tableName);
  71. }
  72. /**
  73. * 按备份类型筛选
  74. */
  75. public function scopeByBackupType($query, BACKUP_TYPE $backupType)
  76. {
  77. return $query->where('backup_type', $backupType->value);
  78. }
  79. /**
  80. * 按压缩类型筛选
  81. */
  82. public function scopeByCompressionType($query, COMPRESSION_TYPE $compressionType)
  83. {
  84. return $query->where('compression_type', $compressionType->value);
  85. }
  86. /**
  87. * 获取文件大小的可读格式
  88. */
  89. public function getFileSizeHumanAttribute(): string
  90. {
  91. $bytes = $this->file_size;
  92. $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  93. for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
  94. $bytes /= 1024;
  95. }
  96. return round($bytes, 2) . ' ' . $units[$i];
  97. }
  98. }