CleanupBackupFile.php 2.7 KB

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