SystemMedia.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Support\Facades\Storage;
  5. class SystemMedia extends Model
  6. {
  7. protected $fillable = [
  8. 'filename', 'ext', 'category_id', 'path', 'size', 'mime_type',
  9. ];
  10. protected $casts = [
  11. 'category_id' => 'integer',
  12. 'size' => 'integer',
  13. ];
  14. protected $perPage = 30;
  15. public function category()
  16. {
  17. return $this->belongsTo(SystemMediaCategory::class, 'category_id');
  18. }
  19. public function delete()
  20. {
  21. DB::beginTransaction();
  22. $deleted = parent::delete();
  23. // 记录删除成功,且数据库中没有相同的文件记录,则要删除对应的文件
  24. $needDeletedFile = $deleted && !$this->hasSameFile();
  25. $fileDeleted = false;
  26. if ($needDeletedFile) {
  27. $storage = Storage::disk('uploads');
  28. // 文件不存在,或者删除成功
  29. if (!$storage->exists($this->path) || $storage->delete($this->path)) {
  30. $fileDeleted = true;
  31. }
  32. }
  33. if (
  34. ($needDeletedFile && $fileDeleted) || // 需要删除物理文件,且删除成功,则提交事务
  35. (!$needDeletedFile && $deleted) // 或不需要物理删除,且当前记录删除成功
  36. ) {
  37. DB::commit();
  38. return true;
  39. } else { // 删除失败
  40. DB::rollBack();
  41. return false;
  42. }
  43. }
  44. /**
  45. * 数据库中是否还有相同文件的记录
  46. *
  47. * @return bool
  48. */
  49. protected function hasSameFile()
  50. {
  51. return !!static::query()
  52. ->where('filename', $this->filename)
  53. ->where('id', '<>', $this->id)
  54. ->first();
  55. }
  56. }