UserActivityData.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace App\Module\Activity\Models;
  3. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  4. use UCore\ModelCore;
  5. /**
  6. * 用户活动数据
  7. *
  8. * field start
  9. * @property int $id 主键
  10. * @property int $user_id 用户ID
  11. * @property int $activity_id 活动ID
  12. * @property int $progress 活动进度(如任务完成数等)
  13. * @property object|array $progress_data 详细进度数据,JSON格式
  14. * @property \Carbon\Carbon $last_update 最后更新时间
  15. * @property \Carbon\Carbon $created_at 创建时间
  16. * @property \Carbon\Carbon $updated_at 更新时间
  17. * field end
  18. */
  19. class UserActivityData extends ModelCore
  20. {
  21. /**
  22. * 与模型关联的表名
  23. *
  24. * @var string
  25. */
  26. protected $table = 'user_activity_data';
  27. /**
  28. * 可批量赋值的属性
  29. *
  30. * @var array
  31. */
  32. // attrlist start
  33. protected $fillable = [
  34. 'id',
  35. 'user_id',
  36. 'activity_id',
  37. 'progress',
  38. 'progress_data',
  39. 'last_update',
  40. ];
  41. // attrlist end
  42. /**
  43. * 应该被转换为原生类型的属性
  44. *
  45. * @var array
  46. */
  47. protected $casts = [
  48. 'user_id' => 'integer',
  49. 'activity_id' => 'integer',
  50. 'progress' => 'integer',
  51. 'progress_data' => 'json',
  52. 'last_update' => 'datetime',
  53. ];
  54. /**
  55. * 获取关联的活动
  56. *
  57. * @return BelongsTo
  58. */
  59. public function activity(): BelongsTo
  60. {
  61. return $this->belongsTo(ActivityConfig::class, 'activity_id', 'id');
  62. }
  63. /**
  64. * 获取关联的参与记录
  65. *
  66. * @return BelongsTo
  67. */
  68. public function participation(): BelongsTo
  69. {
  70. return $this->belongsTo(ActivityParticipation::class, ['user_id', 'activity_id'], ['user_id', 'activity_id']);
  71. }
  72. /**
  73. * 更新进度
  74. *
  75. * @param int $progress 新的进度值
  76. * @param array|null $progressData 详细进度数据
  77. * @return bool
  78. */
  79. public function updateProgress(int $progress, ?array $progressData = null): bool
  80. {
  81. $this->progress = $progress;
  82. if ($progressData !== null) {
  83. $this->progress_data = $progressData;
  84. }
  85. $this->last_update = now();
  86. return $this->save();
  87. }
  88. /**
  89. * 增加进度
  90. *
  91. * @param int $increment 增加的进度值
  92. * @param array|null $progressData 详细进度数据
  93. * @return bool
  94. */
  95. public function incrementProgress(int $increment, ?array $progressData = null): bool
  96. {
  97. return $this->updateProgress($this->progress + $increment, $progressData);
  98. }
  99. }