Browse Source

fix:循环绑定问题

super-yimizi 1 day ago
parent
commit
231abb162a
1 changed files with 42 additions and 0 deletions
  1. 42 0
      application/api/controller/commission/AgentApply.php

+ 42 - 0
application/api/controller/commission/AgentApply.php

@@ -140,6 +140,11 @@ class AgentApply extends Base
             // 检查是否已经有上级了
             if (!empty($user->parent_user_id)) {
                 $this->error('您已经有上级了,无法重复绑定');
+            }
+            
+            // 防止循环绑定:检查目标上级是否已经是当前用户的下级
+            if ($this->isUserInDownline($user->id, $parentAgent->user_id)) {
+                $this->error('不能绑定下级用户为上级');
             }         
             // 更新用户的上级关系
             $user->parent_user_id = $parentAgent->user_id;
@@ -216,6 +221,43 @@ class AgentApply extends Base
 
         return $channelToShareMap[$channelPlatform] ?? ShareEnum::PLATFORM_WECHAT_MINI_PROGRAM;
     }
+    
+    /**
+     * 检查目标用户是否在指定用户的下级链条中(防止循环绑定)
+     * @param int $parentUserId 上级用户ID
+     * @param int $targetUserId 要检查的目标用户ID  
+     * @param int $maxDepth 最大检查深度,防止无限递归
+     * @param int $currentDepth 当前递归深度
+     * @return bool true-目标用户在下级链条中,false-不在
+     */
+    private function isUserInDownline($parentUserId, $targetUserId, $maxDepth = 10, $currentDepth = 0)
+    {
+        // 防止无限递归
+        if ($currentDepth >= $maxDepth) {
+            return false;
+        }
+        
+        // 查找所有以 $parentUserId 为上级的用户
+        $childrenUsers = UserModel::where('parent_user_id', $parentUserId)->column('id');
+        
+        if (empty($childrenUsers)) {
+            return false;
+        }
+        
+        // 直接检查:目标用户是否是直接下级
+        if (in_array($targetUserId, $childrenUsers)) {
+            return true;
+        }
+        
+        // 递归检查:目标用户是否在任何一个下级的下级链条中
+        foreach ($childrenUsers as $childUserId) {
+            if ($this->isUserInDownline($childUserId, $targetUserId, $maxDepth, $currentDepth + 1)) {
+                return true;
+            }
+        }
+        
+        return false;
+    }
 
 
 }