Email和Phone都是允许null,根据类型声明为sql.Nullxxx
1 2 3 4 5 |
type User struct { Email sql.NullString `gorm:"column:email;type:varchar(255);unique;default null;comment:邮箱" json:"email"` Phone sql.NullString `gorm:"column:phone;type:char(11);unique;default null;comment:手机号" json:"phone"` } |
赋值的时候
1 2 3 4 5 |
db.Create(&User{ // string是值 Valid必须为true Email: sql.NullString{String: "123@qq.com", Valid: true}, }) |
但是取值的时候 ,email字段会返回String与Valid两个字段,而我们只需要String的值
1 2 3 4 5 6 7 8 9 10 11 12 |
{ "code": 0, "data": [ { "email": { "String": "1234567@qq.com", "Valid": true } } ], "message": "查询成功" } |
解决问题
自定义sql.Nullxxxx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
type User struct { Email NullString `gorm:"column:email;type:varchar(255);unique;default null;comment:邮箱" json:"email"` Phone NullString `gorm:"column:phone;type:char(11);unique;default null;comment:手机号" json:"phone"` } // 自定义 sql.NullString type NullString sql.NullString // Scan implements the Scanner interface. func (n *NullString) Scan(value interface{}) error { return (*sql.NullString)(n).Scan(value) } // Value implements the driver Valuer interface. func (n NullString) Value() (driver.Value, error) { if !n.Valid { return nil, nil } return n.String, nil } // json序列化 func (n NullString) MarshalJSON() ([]byte, error) { if n.Valid { return json.Marshal(n.String) } return json.Marshal(nil) } // json 反序列化 func (n *NullString) UnmarshalJSON(b []byte) error { if string(b) == "null" { n.Valid = false return nil } err := json.Unmarshal(b, &n.String) if err == nil { n.Valid = true } return err } |
赋值
1 2 3 4 5 |
db.Create(&User{ // 使用自定义的 NullString Email: NullString{String: "a string goes here", Valid: true} }) |
参考
Unable to use type string as sql.NullString
gorm.Model
中的DeletedAt
,查看源码,会发现它是自定义的sql.NullTime
。