UserLogClearRecord.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Module\Game\Models;
  3. use UCore\ModelCore;
  4. /**
  5. * 用户日志清理记录模型
  6. *
  7. * field start
  8. * @property int $id 主键ID
  9. * @property int $user_id 用户ID
  10. * @property \Carbon\Carbon $cleared_at 清理时间
  11. * @property \Carbon\Carbon $created_at 创建时间
  12. * @property \Carbon\Carbon $updated_at 更新时间
  13. * field end
  14. */
  15. class UserLogClearRecord extends ModelCore
  16. {
  17. /**
  18. * 与模型关联的表名
  19. *
  20. * @var string
  21. */
  22. protected $table = 'user_log_clear_records';
  23. /**
  24. * 指示模型是否应该被打上时间戳
  25. *
  26. * @var bool
  27. */
  28. public $timestamps = true;
  29. // attrlist start
  30. protected $fillable = [
  31. 'id',
  32. 'user_id',
  33. 'cleared_at',
  34. ];
  35. // attrlist end
  36. /**
  37. * 应该被转换为日期的属性
  38. *
  39. * @var array
  40. */
  41. protected $casts = [
  42. 'cleared_at' => 'datetime',
  43. 'created_at' => 'datetime',
  44. 'updated_at' => 'datetime',
  45. ];
  46. /**
  47. * 按用户ID查询作用域
  48. *
  49. * @param \Illuminate\Database\Eloquent\Builder $query
  50. * @param int $userId 用户ID
  51. * @return \Illuminate\Database\Eloquent\Builder
  52. */
  53. public function scopeByUser($query, int $userId)
  54. {
  55. return $query->where('user_id', $userId);
  56. }
  57. /**
  58. * 获取用户的最后清理时间
  59. *
  60. * @param int $userId 用户ID
  61. * @return \Carbon\Carbon|null
  62. */
  63. public static function getUserLastClearTime(int $userId): ?\Carbon\Carbon
  64. {
  65. $record = static::byUser($userId)->first();
  66. return $record ? $record->cleared_at : null;
  67. }
  68. /**
  69. * 设置用户的清理时间
  70. *
  71. * @param int $userId 用户ID
  72. * @param \Carbon\Carbon|null $clearTime 清理时间,默认为当前时间
  73. * @return static
  74. */
  75. public static function setUserClearTime(int $userId, ?\Carbon\Carbon $clearTime = null): static
  76. {
  77. $clearTime = $clearTime ?: now();
  78. return static::updateOrCreate(
  79. ['user_id' => $userId],
  80. ['cleared_at' => $clearTime]
  81. );
  82. }
  83. }