任务时间: 2025年07月04日 22:40-23:00 任务类型: 性能优化 模块: AppGame/Handler/Promotion
优化 InfoHandler 中的 getTodayStats 和 getActiveStats 方法,使用 UrsUserRelationCache 模型直接查询数据,替代原有的多次数据库查询方式。
UrsReferralService::getTeamMembers() - 1次查询UrsUserMappingService::getFarmUserId() - N次查询UrsUserMappingService::getMappingDetail() - N次查询// 优化后:只需1次查询
$todayRelations = UrsUserRelationCache::where('related_user_id', $farmUserId)
->whereDate('created_at', today())
->selectRaw('
COUNT(CASE WHEN depth = 1 THEN 1 END) as direct_new_count,
COUNT(CASE WHEN depth <= 3 THEN 1 END) as team_new_count
')
->first();
app/Module/AppGame/Handler/Promotion/InfoHandler.phpgetTodayStats()use App\Module\UrsPromotion\Models\UrsUserRelationCache;
use App\Module\UrsPromotion\Enums\UrsPromotionRelationLevel;
// 获取当前用户的农场用户ID
$farmUserId = UrsUserMappingService::getFarmUserId($ursUserId);
if (!$farmUserId) {
return ['direct_new_count' => 0, 'team_new_count' => 0];
}
// 使用 UrsUserRelationCache 查询今日新增的关系记录
$todayRelations = UrsUserRelationCache::where('related_user_id', $farmUserId)
->whereDate('created_at', today())
->selectRaw('
COUNT(CASE WHEN depth = 1 THEN 1 END) as direct_new_count,
COUNT(CASE WHEN depth <= 3 THEN 1 END) as team_new_count
')
->first();
$directNewCount = $todayRelations->direct_new_count ?? 0;
$teamNewCount = $todayRelations->team_new_count ?? 0;
return [
'direct_new_count' => (int)$directNewCount,
'team_new_count' => (int)$teamNewCount
];
tests/Unit/AppGame/Handler/Promotion/TodayStatsLogicTest.phpPHPUnit 11.5.20 by Sebastian Bergmann and contributors.
....... 7 / 7 (100%)
Time: 00:01.254, Memory: 46.50 MB
OK (7 tests, 15 assertions)
UrsUserRelationCache 表的数据完整性UrsReferralService::getTeamMembers() - 1次查询UrsUserMappingService::getFarmUserId() - N次查询UserActivityService::getLastActivityTime() - N次查询使用 UrsUserRelationCache 和 UserInfo 进行 JOIN 查询:
$activeStats = UrsUserRelationCache::where('related_user_id', $farmUserId)
->where('depth', '<=', 3) // 只统计前3级
->join('kku_user_infos', 'kku_urs_promotion_user_relation_cache.user_id', '=', 'kku_user_infos.user_id')
->where('kku_user_infos.last_activity_time', '>=', $activeThreshold)
->selectRaw('
COUNT(CASE WHEN depth = 1 THEN 1 END) as direct_active_count,
COUNT(*) as team_active_count
')
->first();
使用 php artisan debug:reproduce-error 69211310 进行实际请求测试:
创建了两套完整的单元测试:
tests/Unit/AppGame/Handler/Promotion/TodayStatsLogicTest.php - 7个测试用例tests/Unit/AppGame/Handler/Promotion/ActiveStatsLogicTest.php - 8个测试用例通过使用 UrsUserRelationCache 优化 getTodayStats 和 getActiveStats 两个方法:
优化后的方法在保持功能不变的前提下,为系统性能带来了显著提升,特别是在团队成员较多的情况下效果更加明显。