ShopUserPurchaseCounter.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. <?php
  2. namespace App\Module\Shop\Models;
  3. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  4. use UCore\ModelCore;
  5. /**
  6. * 商店用户购买计数模型
  7. *
  8. * field start
  9. * @property int $id 记录ID,主键
  10. * @property int $limit_id 限购配置ID,外键关联kku_shop_purchase_limits表
  11. * @property int $user_id 用户ID
  12. * @property int $current_count 当前购买计数
  13. * @property string $last_reset_time 上次重置时间
  14. * @property \Carbon\Carbon $created_at 创建时间
  15. * @property \Carbon\Carbon $updated_at 更新时间
  16. * field end
  17. */
  18. class ShopUserPurchaseCounter extends ModelCore
  19. {
  20. /**
  21. * 与模型关联的表名
  22. *
  23. * @var string
  24. */
  25. protected $table = 'shop_user_purchase_counters';
  26. /**
  27. * 可批量赋值的属性
  28. *
  29. * @var array
  30. */
  31. protected $fillable = [
  32. 'limit_id',
  33. 'user_id',
  34. 'current_count',
  35. 'last_reset_time',
  36. ];
  37. /**
  38. * 应该被转换为日期的属性
  39. *
  40. * @var array
  41. */
  42. protected $dates = [
  43. 'last_reset_time',
  44. 'created_at',
  45. 'updated_at',
  46. ];
  47. /**
  48. * 应该被转换为原生类型的属性
  49. *
  50. * @var array
  51. */
  52. protected $casts = [
  53. 'current_count' => 'integer',
  54. ];
  55. /**
  56. * 获取关联的限购配置
  57. *
  58. * @return BelongsTo
  59. */
  60. public function purchaseLimit(): BelongsTo
  61. {
  62. return $this->belongsTo(ShopPurchaseLimit::class, 'limit_id');
  63. }
  64. /**
  65. * 增加计数
  66. *
  67. * @param int $count 增加的数量
  68. * @return bool
  69. */
  70. public function incrementCount(int $count = 1): bool
  71. {
  72. $this->current_count += $count;
  73. return $this->save();
  74. }
  75. /**
  76. * 重置计数
  77. *
  78. * @return bool
  79. */
  80. public function resetCount(): bool
  81. {
  82. $this->current_count = 0;
  83. $this->last_reset_time = now();
  84. return $this->save();
  85. }
  86. /**
  87. * 检查是否达到限制
  88. *
  89. * @return bool
  90. */
  91. public function isLimitReached(): bool
  92. {
  93. $limit = $this->purchaseLimit;
  94. if (!$limit) {
  95. return false;
  96. }
  97. return $this->current_count >= $limit->max_quantity;
  98. }
  99. /**
  100. * 获取剩余可购买数量
  101. *
  102. * @return int
  103. */
  104. public function getRemainingQuantity(): int
  105. {
  106. $limit = $this->purchaseLimit;
  107. if (!$limit) {
  108. return 0;
  109. }
  110. return max(0, $limit->max_quantity - $this->current_count);
  111. }
  112. }