gorm update传入struct对象,零值字段不更新的解决方案

时间:2021-12-11 20:26:00

使用gorm的update接口,出现如果字段为零值

则不会生成字段的更新语句

 

?
1
2
3
4
5
// Update update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
// WARNING when update with struct, GORM will not update fields that with zero value
func (s *DB) Update(attrs ...interface{}) *DB {
 return s.Updates(toSearchableMap(attrs...), true)
}

如:

?
1
2
3
4
5
type AA struct {
 ID             int       `gorm:"primary_key" json:" - "`            //主键id
    Code1       string  
 Code2     string                        
}

如果

?
1
2
3
4
5
a :=AA{
    ID:1,
    Code1:1,
    Code2:0
}

则产生的SQL语句将不包含Code2更新语句,

?
1
update aa set Code1 =1 where id =1;

出现该问题的原因在于

 

使用stuct类型对象作为参数时,struct会首先转化为map对象,然后再生成SQL语句,但是转化为map的过程中,对于零值字段是忽略的

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// assignUpdatingAttributesCallback assign updating attributes to model
func assignUpdatingAttributesCallback(scope *Scope) {
    if attrs, ok := scope.InstanceGet("gorm:update_interface"); ok {
        if updateMaps, hasUpdate := scope.updatedAttrsWithValues(attrs); hasUpdate {
            scope.InstanceSet("gorm:update_attrs", updateMaps)
        } else {
            scope.SkipLeft()
        }
    }
}
func (scope *Scope) updatedAttrsWithValues(value interface{}) (results map[string]interface{}, hasUpdate bool) {
    if scope.IndirectValue().Kind() != reflect.Struct {
        return convertInterfaceToMap(value, false, scope.db), true
    }
 
    results = map[string]interface{}{}
 
    for key, value := range convertInterfaceToMap(value, true, scope.db) {
        if field, ok := scope.FieldByName(key); ok && scope.changeableField(field) {
            if _, ok := value.(*SqlExpr); ok {
                hasUpdate = true
                results[field.DBName] = value
            } else {
                err := field.Set(value)
                if field.IsNormal && !field.IsIgnored {
                    hasUpdate = true
                    if err == ErrUnaddressable {
                        results[field.DBName] = value
                    } else {
                        results[field.DBName] = field.Field.Interface()
                    }
                }
            }
        }
    }
    return
func convertInterfaceToMap(values interface{}, withIgnoredField bool, db *DB) map[string]interface{} {
    var attrs = map[string]interface{}{}
 
    switch value := values.(type) {
    case map[string]interface{}:
        return value
    case []interface{}:
        for _, v := range value {
            for key, value := range convertInterfaceToMap(v, withIgnoredField, db) {
                attrs[key] = value
            }
        }
    case interface{}:
        reflectValue := reflect.ValueOf(values)
 
        switch reflectValue.Kind() {
        case reflect.Map:
            for _, key := range reflectValue.MapKeys() {
                attrs[ToColumnName(key.Interface().(string))] = reflectValue.MapIndex(key).Interface()
            }
        default:
            for _, field := range (&Scope{Value: values, db: db}).Fields() {
                if !field.IsBlank && (withIgnoredField || !field.IsIgnored) {
                    //只有非零值才更新
                    attrs[field.DBName] = field.Field.Interface()
                }
            }
        }
    }
    return attrs
}

为了更新零值字段,则需要修改gorm库,我们这里添加一个FORCE标识字段必须更新

?
1
2
3
4
5
type AA struct {
 ID             int       `gorm:"primary_key" json:" - "`            //主键id
    Code1       string    `gorm:"force"`
 Code2     string    `gorm:"force"`                      
}

修改Sope的Fields函数,对于有FORCE标签的字段,IsBlank直接设置为fasle

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Fields get value's fields
//通过反射获取field的值
func (scope *Scope) Fields() []*Field {
    if scope.fields == nil {
        var (
            fields             []*Field
            indirectScopeValue = scope.IndirectValue()
            isStruct           = indirectScopeValue.Kind() == reflect.Struct
        )
        // 解析结构体
        for _, structField := range scope.GetModelStruct().StructFields {
            if isStruct {
                fieldValue := indirectScopeValue
                // 一般只有一个字段名吧?????
                for _, name := range structField.Names {
                    if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() {
                        // 处理数组
                        fieldValue.Set(reflect.New(fieldValue.Type().Elem()))
                    }
                    //
                    fieldValue = reflect.Indirect(fieldValue).FieldByName(name)
                }
 
                //有force代表强制更新
                _, ok := structField.TagSettingsGet("FORCE")
                fields = append(fields, &Field{StructField: structField, Field: fieldValue, IsBlank: isBlank(fieldValue) && !ok})
                //如果不是struct,则返回空,因为原生没有字段这个说法
            } else {
                fields = append(fields, &Field{StructField: structField, IsBlank: true})
            }
        }
        scope.fields = &fields
    }
    return *scope.fields
}

补充:Gorm 自动update操作自动过滤0和 “ “

gorm会自动过滤结构体的0 和" "

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
type CrmUserTableColumns struct {
    Id                        int64  `gorm:"column:ids"`
    Name                      string `gorm:"column:xxx"`
    Account                   string `gorm:"column:xxx"`
    Password                  string `gorm:"column:xxx"`
    State                     int64  `gorm:"column:state"`
    BusinessId                int64  `gorm:"column:business_id"`
    DepartmentId              int64  `gorm:"column:department_id"`
    ...
}
func (u *CrmUserTableColumns) TableName() string {
    return "crm_user"
}
field := map[string]interface{}{
        "business_id":   data.BusinessId,
        "state":         data.State,
        "department_id": data.DepartmentId,
    }
    whereSql = "account = ?"
updates := dbMasterClient.
        //Debug().
        Model(&CrmUserTableColumns{}).
        Where(whereSql, whereCase).
        Updates(field)
    RowsAffected = updates.RowsAffected
    return

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/idwtwt/article/details/104018291