对象的部分更新
时间:2024-04-05
浏览:343
作者:佚名
各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题是《对象的部分更新》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!
问题内容
我想在我的 fiber/gorm 后端为我的 user 对象启用更新功能。当我使用 save 函数一起更新所有字段时,它工作正常。但是,当我的更新请求中没有出现所有字段(例如,只有 birthday 字段,而不是 phone 字段)时,它会用各自的空值覆盖其余字段。
func userupdatebyid(c *fiber.ctx) error {
db := database.dbconn
// parse the body to fit user entity
user := entities.user{}
if err := c.bodyparser(&user); err != nil {
return c.status(500).sendstring(err.error())
}
// update record
record := db.save(&user)
if record.error != nil {
return c.status(500).sendstring(record.error.error())
}
return c.json(record.value)
当我将 record := db.save(&user) 行更改为
mappeddata, _ := structtomap(user)
record := db.model(&entities.user{}).update(mappeddata)
我收到 update 无法处理接口映射的错误:sql:转换参数 $10 类型:不支持的类型 map[string]interface {},map
更新 1: 提到的 structtomap 函数如下所示:
func structtomap(obj interface{}) (newmap map[string]interface{}, err error) {
data, err := json.marshal(obj)
if err != nil {
return
}
err = json.unmarshal(data, &newmap) // convert to a map
return
}
更新 2: 用户对象如下所示:
type User struct {
gorm.Model
Identity string
Birthday time.Time
Phone string
City string
...
ActivityData []Activity
}解决方案
看看,在 gorm doc(https://gorm.io/docs/update.html) 上,你可以这样做: 使用更新而不是更新。
db.Model(&user).Updates(User{Name: "hello", Age: 18, Active: false})
您还可以使用db.debug来显示gorm所做的最终查询,并查看是否与您期望的匹配。
以上就是《对象的部分更新》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
热门专题
