@@ -173,11 +173,14 @@ func (s *AggregateGroupService) AddSubGroups(ctx context.Context, groupID uint,
173173
174174 // Check if there are existing sub groups and get their validation endpoint
175175 var existingEndpoint string
176- var existingSubGroup models.GroupSubGroup
177- if err := s .db .WithContext (ctx ).Where ("group_id = ?" , groupID ).First (& existingSubGroup ).Error ; err == nil {
178- // If we have existing sub groups, get one of their validation endpoints
176+ var existingSubGroups []models.GroupSubGroup
177+ if err := s .db .WithContext (ctx ).Where ("group_id = ?" , groupID ).Find (& existingSubGroups ).Error ; err != nil {
178+ return err
179+ }
180+
181+ if len (existingSubGroups ) > 0 {
179182 var existingGroup models.Group
180- if err := s .db .WithContext (ctx ).First (& existingGroup , existingSubGroup .SubGroupID ).Error ; err == nil {
183+ if err := s .db .WithContext (ctx ).First (& existingGroup , existingSubGroups [ 0 ] .SubGroupID ).Error ; err == nil {
181184 existingEndpoint = utils .GetValidationEndpoint (& existingGroup )
182185 }
183186 }
@@ -188,12 +191,6 @@ func (s *AggregateGroupService) AddSubGroups(ctx context.Context, groupID uint,
188191 return err
189192 }
190193
191- // Manually query existing sub groups
192- var existingSubGroups []models.GroupSubGroup
193- if err := s .db .WithContext (ctx ).Where ("group_id = ?" , groupID ).Find (& existingSubGroups ).Error ; err != nil {
194- return err
195- }
196-
197194 // Check for duplicates with existing sub groups
198195 existingSubGroupIDs := make (map [uint ]bool )
199196 for _ , sg := range existingSubGroups {
@@ -208,21 +205,27 @@ func (s *AggregateGroupService) AddSubGroups(ctx context.Context, groupID uint,
208205 }
209206
210207 // Add new sub groups
211- return s .db .WithContext (ctx ).Transaction (func (tx * gorm.DB ) error {
208+ err = s .db .WithContext (ctx ).Transaction (func (tx * gorm.DB ) error {
212209 for _ , newSg := range result .SubGroups {
213210 newSg .GroupID = groupID
214211 if err := tx .Create (& newSg ).Error ; err != nil {
215212 return app_errors .ParseDBError (err )
216213 }
217214 }
218215
219- // 触发缓存更新
220- if err := s .groupManager .Invalidate (); err != nil {
221- logrus .WithContext (ctx ).WithError (err ).Error ("failed to invalidate group cache after adding sub groups" )
222- }
223-
224216 return nil
225217 })
218+
219+ if err != nil {
220+ return err
221+ }
222+
223+ // 触发缓存更新
224+ if err := s .groupManager .Invalidate (); err != nil {
225+ logrus .WithContext (ctx ).WithError (err ).Error ("failed to invalidate group cache after adding sub groups" )
226+ }
227+
228+ return nil
226229}
227230
228231// UpdateSubGroupWeight updates the weight of a specific sub group
0 commit comments