| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125 |
- <?php
- namespace App\Module\Shop\Models;
- use Illuminate\Database\Eloquent\Relations\BelongsTo;
- use UCore\ModelCore;
- /**
- * 商店用户购买计数模型
- *
- * field start
- * @property int $id 记录ID,主键
- * @property int $limit_id 限购配置ID,外键关联kku_shop_purchase_limits表
- * @property int $user_id 用户ID
- * @property int $current_count 当前购买计数
- * @property string $last_reset_time 上次重置时间
- * @property \Carbon\Carbon $created_at 创建时间
- * @property \Carbon\Carbon $updated_at 更新时间
- * field end
- */
- class ShopUserPurchaseCounter extends ModelCore
- {
- /**
- * 与模型关联的表名
- *
- * @var string
- */
- protected $table = 'shop_user_purchase_counters';
- /**
- * 可批量赋值的属性
- *
- * @var array
- */
- protected $fillable = [
- 'limit_id',
- 'user_id',
- 'current_count',
- 'last_reset_time',
- ];
- /**
- * 应该被转换为日期的属性
- *
- * @var array
- */
- protected $dates = [
- 'last_reset_time',
- 'created_at',
- 'updated_at',
- ];
- /**
- * 应该被转换为原生类型的属性
- *
- * @var array
- */
- protected $casts = [
- 'current_count' => 'integer',
- ];
- /**
- * 获取关联的限购配置
- *
- * @return BelongsTo
- */
- public function purchaseLimit(): BelongsTo
- {
- return $this->belongsTo(ShopPurchaseLimit::class, 'limit_id');
- }
- /**
- * 增加计数
- *
- * @param int $count 增加的数量
- * @return bool
- */
- public function incrementCount(int $count = 1): bool
- {
- $this->current_count += $count;
- return $this->save();
- }
- /**
- * 重置计数
- *
- * @return bool
- */
- public function resetCount(): bool
- {
- $this->current_count = 0;
- $this->last_reset_time = now();
- return $this->save();
- }
- /**
- * 检查是否达到限制
- *
- * @return bool
- */
- public function isLimitReached(): bool
- {
- $limit = $this->purchaseLimit;
- if (!$limit) {
- return false;
- }
- return $this->current_count >= $limit->max_quantity;
- }
- /**
- * 获取剩余可购买数量
- *
- * @return int
- */
- public function getRemainingQuantity(): int
- {
- $limit = $this->purchaseLimit;
- if (!$limit) {
- return 0;
- }
- return max(0, $limit->max_quantity - $this->current_count);
- }
- }
|