Attachment.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace app\common\model;
  3. use Throwable;
  4. use think\Model;
  5. use ba\Filesystem;
  6. use app\admin\model\Admin;
  7. use think\model\relation\BelongsTo;
  8. /**
  9. * Attachment模型
  10. */
  11. class Attachment extends Model
  12. {
  13. protected $autoWriteTimestamp = true;
  14. protected $updateTime = false;
  15. protected $append = [
  16. 'suffix',
  17. 'full_url'
  18. ];
  19. public function getSuffixAttr($value, $row): string
  20. {
  21. if ($row['name']) {
  22. $suffix = strtolower(pathinfo($row['name'], PATHINFO_EXTENSION));
  23. return $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  24. }
  25. return 'file';
  26. }
  27. public function getFullUrlAttr($value, $row): string
  28. {
  29. return full_url($row['url']);
  30. }
  31. /**
  32. * 入库前
  33. * @throws Throwable
  34. */
  35. protected static function onBeforeInsert($model): bool
  36. {
  37. $repeat = $model->where([
  38. ['sha1', '=', $model->sha1],
  39. ['topic', '=', $model->topic],
  40. ['storage', '=', $model->storage],
  41. ])->find();
  42. if ($repeat) {
  43. $storageFile = Filesystem::fsFit(public_path() . ltrim($repeat['url'], '/'));
  44. if ($model->storage == 'local' && !file_exists($storageFile)) {
  45. $repeat->delete();
  46. return true;
  47. } else {
  48. $repeat->quote++;
  49. $repeat->last_upload_time = time();
  50. $repeat->save();
  51. return false;
  52. }
  53. }
  54. return true;
  55. }
  56. protected static function onAfterInsert($model)
  57. {
  58. if (!$model->last_upload_time) {
  59. $model->quote = 1;
  60. $model->last_upload_time = time();
  61. $model->save();
  62. }
  63. }
  64. public function admin(): BelongsTo
  65. {
  66. return $this->belongsTo(Admin::class);
  67. }
  68. public function user(): BelongsTo
  69. {
  70. return $this->belongsTo(User::class);
  71. }
  72. }