使用gorm的update接口,出現(xiàn)如果字段為零值
則不會生成字段的更新語句
// 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)
}
如:
type AA struct {
ID int `gorm:"primary_key" json:" - "` //主鍵id
Code1 string
Code2 string
}
如果
a :=AA{
ID:1,
Code1:1,
Code2:0
}
則產(chǎn)生的SQL語句將不包含Code2更新語句,
update aa set Code1 =1 where id =1;
出現(xiàn)該問題的原因在于
使用stuct類型對象作為參數(shù)時,struct會首先轉化為map對象,然后再生成SQL語句,但是轉化為map的過程中,對于零值字段是忽略的
// 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標識字段必須更新
type AA struct {
ID int `gorm:"primary_key" json:" - "` //主鍵id
Code1 string `gorm:"force"`
Code2 string `gorm:"force"`
}
修改Sope的Fields函數(shù),對于有FORCE標簽的字段,IsBlank直接設置為fasle
// 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() {
// 處理數(shù)組
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 和" "
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
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- gorm操作MySql數(shù)據(jù)庫的方法
- Go基于GORM 獲取當前請求所執(zhí)行的 SQL 信息(思路詳解)
- Golang 使用gorm添加數(shù)據(jù)庫排他鎖,for update
- golang Gorm與數(shù)據(jù)庫完整性約束詳解
- golang gorm 結構體的表字段缺省值設置方式
- golang gorm 計算字段和獲取sum()值的實現(xiàn)
- gorm FirstOrCreate和受影響的行數(shù)實例
- 解決Go gorm踩過的坑