Browse Source

选择父级需求分组时会带出子级分组的需求

kely 1 year ago
parent
commit
fb8ef80bc3
1 changed files with 36 additions and 1 deletions
  1. 36 1
      app/ModelFilters/RequirementFilter.php

+ 36 - 1
app/ModelFilters/RequirementFilter.php

@@ -2,6 +2,8 @@
 
 namespace App\ModelFilters;
 
+use App\Models\Requirement;
+use App\Models\RequirementGroup;
 use EloquentFilter\ModelFilter;
 
 class RequirementFilter extends ModelFilter
@@ -24,7 +26,40 @@ class RequirementFilter extends ModelFilter
     }
 
     public function groupId($groupId){
-        return $this->where('requirement_group_id',$groupId);
+        //
+        $group = RequirementGroup::find($groupId);
+        if (!$group || !$group->children()->first()) {
+            // 如果没有子级,只返回该分组的需求
+            return $this->where('requirement_group_id', $groupId);
+        }
+
+        $allRelatedGroupIds = $this->getAllRelatedGroupIds($groupId);
+        //把父级id去重
+        $unIds=array_unique($allRelatedGroupIds);
+        return $this->whereIn('requirement_group_id',$unIds);
     }
 
+    private function getAllRelatedGroupIds($groupId)
+    {
+        $group = RequirementGroup::find($groupId);
+
+        if (!$group) {
+            return [];
+        }
+
+        // 获取所有子级ID
+        $childIds = $group->children()->pluck('id')->toArray();
+
+        // 递归获取所有子级的子级ID
+        foreach ($childIds as $childId) {
+            $childIds = array_merge($childIds, $this->getAllRelatedGroupIds($childId));
+        }
+
+        // 添加父级ID(如果需要的话)
+        if ($group->parent_id) {
+            $childIds[] = $group->parent_id;
+        }
+
+        return $childIds;
+    }
 }