URS推广模块的关系缓存系统现已支持20代推荐关系的预计算和存储。本文档详细说明关系缓存的创建时机、触发条件和维护机制。
触发位置: UrsReferralService::createReferral()
触发条件: 新用户建立推荐关系时
创建范围: 为新用户创建完整的20代上级关系缓存
// 在推荐关系创建成功后自动触发
DB::commit();
// 生成关系缓存
$relationCacheLogic = new UrsRelationCacheLogic();
$relationCacheLogic->generateUserRelationCache($ursUserId);
创建逻辑:
触发位置: UrsUserMappingService::createMapping()
触发条件: URS用户首次进入农场建立映射关系时
更新范围: 更新相关缓存记录中的农场用户ID字段
// 用户进入农场后更新缓存中的农场用户ID
$relationCacheLogic = new UrsRelationCacheLogic();
$relationCacheLogic->updateFarmUserIdInCache($ursUserId, $farmUserId);
# 重建所有用户的关系缓存
php artisan urs:rebuild-relation-cache
# 检查缓存完整性
php artisan urs:rebuild-relation-cache --check
# 修复缓存问题
php artisan urs:rebuild-relation-cache --fix
/admin/urs-promotion/user-relation-cache# 为特定用户生成缓存
php artisan urs:test-relation-cache generate --user-id=10016
# 批量生成缓存
php artisan urs:test-relation-cache batch --users=10016,10015,10014
-- 示例:用户A的20代关系缓存
user_id | related_user_id | urs_user_id | urs_related_user_id | level | depth | path | urs_path
--------|-----------------|-------------|---------------------|-------|-------|------|----------
2001 | 2002 | 1001 | 1002 | 1 | 1 | 2002 | 1002
2001 | 2003 | 1001 | 1003 | 2 | 2 | 2002,2003 | 1002,1003
2001 | 2004 | 1001 | 1004 | 2 | 3 | 2002,2003,2004 | 1002,1003,1004
... | ... | ... | ... | 2 | 20 | 2002,...,2021 | 1002,...,1021
public function generateUserRelationCache(int $ursUserId): bool
{
// 1. 清除现有缓存
$this->clearUserRelationCache($ursUserId);
// 2. 获取直接推荐人
$referral = UrsUserReferral::where('urs_user_id', $ursUserId)->first();
if (!$referral) return true;
// 3. 创建1级关系缓存
$this->createDirectRelationCache($ursUserId, $referral);
// 4. 获取推荐人的所有上级(最多19级)
$upperRelations = UrsUserRelationCache::where('urs_user_id', $ursReferrerId)
->where('depth', '<', 20)
->get();
// 5. 创建2-20级间接关系缓存
foreach ($upperRelations as $upperRelation) {
$newDepth = $upperRelation->depth + 1;
if ($newDepth <= 20) {
$this->createIndirectRelationCache($ursUserId, $upperRelation, $newDepth);
}
}
return true;
}
// 检查项目
- 缺失缓存的用户数量
- 孤立缓存记录数量
- 循环推荐关系数量
- 深度超限的缓存记录
// 优化后的收益分发查询
$relations = UrsUserRelationCache::where('user_id', $userId)
->where('depth', '<=', 20)
->orderBy('depth')
->get();
foreach ($relations as $relation) {
// 为每一级推荐人分发收益
$this->distributeProfit($relation->related_user_id, $relation->depth);
}
// 快速统计团队规模
$teamStats = UrsUserRelationCache::where('related_user_id', $userId)
->selectRaw('depth, count(*) as count')
->groupBy('depth')
->get();
// 查询用户的所有下级(按代数分组)
$downlines = UrsUserRelationCache::where('related_user_id', $userId)
->where('depth', '<=', 20)
->get()
->groupBy('depth');