CleanupBackupFile.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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. * @property int $id 主键ID
  20. * @property int $backup_id 备份记录ID
  21. * @property string $table_name 表名
  22. * @property string $file_name 文件名
  23. * @property string $file_path 文件路径
  24. * @property int $file_size 文件大小(字节)
  25. * @property string $file_hash 文件SHA256哈希
  26. * @property int $backup_type 备份类型:1SQL,2JSON,3CSV
  27. * @property int $compression_type 压缩类型:1none,2gzip,3zip
  28. * @property \Carbon\Carbon $created_at 创建时间
  29. * field end
  30. /**
  31. * 字段类型转换
  32. */
  33. protected $casts = [
  34. 'backup_id' => 'integer',
  35. 'file_size' => 'integer',
  36. 'backup_type' => 'integer',
  37. 'compression_type' => 'integer',
  38. 'created_at' => 'datetime',
  39. 'updated_at' => 'datetime',
  40. ];
  41. /**
  42. * 获取备份类型枚举
  43. */
  44. public function getBackupTypeEnumAttribute(): BACKUP_TYPE
  45. {
  46. return BACKUP_TYPE::from($this->backup_type);
  47. }
  48. /**
  49. * 获取压缩类型枚举
  50. */
  51. public function getCompressionTypeEnumAttribute(): COMPRESSION_TYPE
  52. {
  53. return COMPRESSION_TYPE::from($this->compression_type);
  54. }
  55. /**
  56. * 关联备份记录
  57. */
  58. public function backup(): BelongsTo
  59. {
  60. return $this->belongsTo(CleanupBackup::class, 'backup_id');
  61. }
  62. /**
  63. * 按表名筛选
  64. */
  65. public function scopeByTable($query, string $tableName)
  66. {
  67. return $query->where('table_name', $tableName);
  68. }
  69. /**
  70. * 按备份类型筛选
  71. */
  72. public function scopeByBackupType($query, BACKUP_TYPE $backupType)
  73. {
  74. return $query->where('backup_type', $backupType->value);
  75. }
  76. /**
  77. * 按压缩类型筛选
  78. */
  79. public function scopeByCompressionType($query, COMPRESSION_TYPE $compressionType)
  80. {
  81. return $query->where('compression_type', $compressionType->value);
  82. }
  83. /**
  84. * 获取文件大小的可读格式
  85. */
  86. public function getFileSizeHumanAttribute(): string
  87. {
  88. $bytes = $this->file_size;
  89. $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  90. for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
  91. $bytes /= 1024;
  92. }
  93. return round($bytes, 2) . ' ' . $units[$i];
  94. }
  95. }