我试图做一个可以通过给定参数更新用户的函数。
我的方法:
func UpdateMultiple(db *gorm.DB, user *User, id uint32) error {
usr := User{}
err := db.Debug().Model(User{}).Where("id = ?", id).Updates(map[string]interface{}{"email": user.Email, "is_active": false}).Take(&usr).Error
if err != nil {
return err
}
return nil
}
像这样使用:
Updater := &User{
Email: holder.Email,
IsActive: false,
}
err = UpdateMultiple(s.DB, Updater, id)
现在它可以正常工作。但是如果要更新另一个字段,我必须更改我的UpdateMultiple()方法。我还有其他方法可以在不更改方法而仅更改给定参数值的情况下进行更新吗?
由于您需要动态更新字段,因此请先按ID提取用户
更新您要更新的字段
并更新用户信息
You can pass your
User
model to theUpdates
function, it will update all struct fields with non blank value (which means that all fields should be pointers, in order to make the best use of this feature). The code would look like this:}