belongsTo('LotteryActivity', 'activity_id'); } /** * 关联用户 */ public function user() { return $this->belongsTo('app\common\model\User', 'user_id'); } /** * 获取获得详情数据 */ public function getGetDetailDataAttr($value, $data) { return !empty($data['get_detail']) ? json_decode($data['get_detail'], true) : []; } /** * 设置获得详情 */ public function setGetDetailAttr($value) { return is_array($value) ? json_encode($value) : $value; } /** * 获取用户抽奖机会 */ public static function getUserChance($activityId, $userId) { return static::where('activity_id', $activityId) ->where('user_id', $userId) ->find(); } /** * 增加抽奖机会 */ public static function addChance($activityId, $userId, $times = 1, $detail = []) { $chance = static::getUserChance($activityId, $userId); if (!$chance) { // 创建新记录 $data = [ 'activity_id' => $activityId, 'user_id' => $userId, 'total_chances' => $times, 'used_chances' => 0, 'remain_chances' => $times, 'last_get_time' => time(), 'get_detail' => json_encode([$detail]) ]; return static::create($data); } else { // 更新现有记录 $chance->total_chances += $times; $chance->remain_chances += $times; $chance->last_get_time = time(); // 更新获得详情 $getDetail = $chance->get_detail_data; $getDetail[] = $detail; $chance->get_detail = json_encode($getDetail); return $chance->save() ? $chance : false; } } /** * 使用抽奖机会 */ public function useChance($times = 1) { if ($this->remain_chances < $times) { return false; } $this->used_chances += $times; $this->remain_chances -= $times; $this->last_use_time = time(); return $this->save(); } /** * 检查是否有剩余机会 */ public function hasChance($times = 1) { return $this->remain_chances >= $times; } /** * 重置抽奖机会(用于测试或特殊情况) */ public function resetChance() { $this->used_chances = 0; $this->remain_chances = $this->total_chances; return $this->save(); } /** * 获取活动总参与人数 */ public static function getActivityParticipants($activityId) { return static::where('activity_id', $activityId)->count(); } /** * 获取用户在多个活动中的机会统计 */ public static function getUserChancesStats($userId, $activityIds = []) { $query = static::where('user_id', $userId); if (!empty($activityIds)) { $query->where('activity_id', 'in', $activityIds); } return $query->field([ 'activity_id', 'total_chances', 'used_chances', 'remain_chances' ]) ->select(); } /** * 批量创建用户机会(用于活动启动时) */ public static function batchCreateChances($activityId, $userIds, $times = 1) { $data = []; $now = time(); foreach ($userIds as $userId) { $data[] = [ 'activity_id' => $activityId, 'user_id' => $userId, 'total_chances' => $times, 'used_chances' => 0, 'remain_chances' => $times, 'last_get_time' => $now, 'createtime' => $now, 'updatetime' => $now ]; } return static::insertAll($data); } }