登录
首页 >  Golang >  Go问答

设置数据库记录为 NULL 的数据操作不会被 nil 执行

来源:stackoverflow

时间:2024-02-23 11:00:26 143浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《设置数据库记录为 NULL 的数据操作不会被 nil 执行》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

我正在使用 gorm,并且我有一个可为 null 的列 gender,可以设置 malefemale,但是一旦该列设置为 malez 的值,我就无法使用 nil 将其设置回 null qbendczqb 或 female

以下是我的代码。为了稍微简化一下,我只包含与我的问题相关的字段

type user struct {
    gorm.model

    username    string       `gorm:"type:varchar(40);unique" json:"username"`
    nickname    string       `gorm:"type:varchar(32)" json:"nickname"`
    gender      *string      `gorm:"type:enum('male', 'female');default:null" json:"gender"`
}

然后我将性别更新为男性:

db.model(&user{}).where(&user{
    model: gorm.model{id: 1},
}).update(
    &user{
        gender:   utils.getstringptr("female"),
        nickname: "nick name",
    },
)

然后我尝试将性别更新为 null

db.Model(&User{}).Where(&User{
    Model: gorm.Model{ID: 1},
}).Update(
    &User{
        Gender:   nil,
        NickName: "nick name",
    },
)

但是,性别保持不变 female更改为 null

有什么想法可以解决这个问题吗?


解决方案


从官方文档中,我找到了这个 http://gorm.io/docs/update.html

// update multiple attributes with `struct`, will only update those changed & non blank fields
db.model(&user).updates(user{name: "hello", age: 18})
//// update users set name='hello', age=18, updated_at = '2013-11-17 21:34:10' where id = 111;

// warning when update with struct, gorm will only update those fields that with non blank value
// for below update, nothing will be updated as "", 0, false are blank values of their types
db.model(&user).updates(user{name: "", age: 0, actived: false})

如果我这样做:

db.Model(&user).Updates(map[string]interface{"gender": nil})

这可以成功地将模型列更新为 null。

但是,我意识到这有点糟糕,因为如果我将 bool 列设置为 true,这意味着我将永远无法使用结构更新将其设置回 false。有什么办法可以解决这个问题吗?这样做的设计目的是什么?

以上就是《设置数据库记录为 NULL 的数据操作不会被 nil 执行》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>