my data struct is as follows
type DynamicConfig struct {
gorm.Model
AppName string `json:"app_name" form:"app_name"`
Creator string `gorm:"<-:create" json:"creator" form:"creator"`
Editor string `json:"editor" form:"editor"`
Metadata string `json:"metadata" form:"metadata"`
}
My idea is that the creator cannot be changed after being created, so i use gorm:"<-:create", docs says it can allow read and create. There is such a piece of data in the database.
{
"ID": 4,
"CreatedAt": "2021-11-30T13:05:31Z",
"UpdatedAt": "2021-12-01T06:22:02Z",
"DeletedAt": null,
"app_name": "test3",
"creator": "xx",
"editor": "yy",
"metadata": "test3"
}
Here is my update method:
func UpdateDynamicConfig(dc DynamicConfig) error {
res, err := GetDynamicConfig(DynamicConfig{
AppName: dc.AppName,
})
if err != nil {
return err
}else if len(res) == 0 {
return errors.New("app conf not exists")
}else if len(res) != 1 {
return errors.New("more than one config meet the criteria, please check")
}
config := res[0]
result := DB.Model(&config).Updates(dc)
return result.Error
}
I call the method like this
config := model.DynamicConfig{AppName: "test3", Creator: "xxxx"}
model.UpdateDynamicConfig(config)
then the creator is update to xxxx. How can i prevent a field from being updated? Please help me, thank you very much!
CodePudding user response:
Please use Omit it will not consider the column while updating the data in table. Please refer this link for Omit
result := DB.Model(&config).Omit("creator").Updates(dc)
OR
For field level permission please refer this link.
You can try with this
Name string `gorm:"->;<-:create"` // allow read and create
CodePudding user response:
The easiest way to omit a field in the update is to use the Omit function:
result := DB.Model(&config).Omit("Creator").Updates(dc)