Skip to content

Commit dd52095

Browse files
author
武斌
committed
feat: 在processEntities方法中初始化影响行数并优化错误处理逻辑,确保成功处理单个实体时正确更新影响行数
1 parent 774cb6f commit dd52095

1 file changed

Lines changed: 16 additions & 5 deletions

File tree

unitofwork/plugin.go

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,9 @@ func (p *Plugin) processEntities(db *gorm.DB, processor func(Entity) error) erro
158158
return nil
159159
}
160160

161+
// 初始化影响行数为0
162+
db.RowsAffected = 0
163+
161164
destValue := reflect.ValueOf(db.Statement.Dest)
162165
if destValue.Kind() == reflect.Ptr {
163166
destValue = destValue.Elem()
@@ -167,7 +170,12 @@ func (p *Plugin) processEntities(db *gorm.DB, processor func(Entity) error) erro
167170
case reflect.Struct:
168171
// 单个实体
169172
if entity, ok := db.Statement.Dest.(Entity); ok {
170-
return processor(entity)
173+
if err := processor(entity); err != nil {
174+
return err
175+
}
176+
// 成功处理单个实体,设置影响行数为1
177+
db.RowsAffected = 1
178+
return nil
171179
}
172180
return nil
173181
case reflect.Slice:
@@ -192,14 +200,17 @@ func (p *Plugin) processEntities(db *gorm.DB, processor func(Entity) error) erro
192200
}
193201
}
194202
// 设置影响的行数
195-
if processedCount > 0 {
196-
db.RowsAffected = int64(processedCount)
197-
}
203+
db.RowsAffected = int64(processedCount)
198204
return nil
199205
default:
200206
// 尝试直接转换
201207
if entity, ok := db.Statement.Dest.(Entity); ok {
202-
return processor(entity)
208+
if err := processor(entity); err != nil {
209+
return err
210+
}
211+
// 成功处理实体,设置影响行数为1
212+
db.RowsAffected = 1
213+
return nil
203214
}
204215
return nil
205216
}

0 commit comments

Comments
 (0)