我在Golang中使用Gorm处理postgresql db.我使用pgtype包来处理可空字段. 要在字段中插入空值,我必须将状态设置为pgtype.null,如下所示.
type Person struct {
ID string
Age int
Nickname pgtype.Text
}
func CreatePerson(){
john := &Person{
ID: "John",
Age: 30,
Nickname: pgtype.Text{Status: pgtype.Null},
}
DB.Create(john) // ID: John, Age: 30, Nickname: NULL
}
但是,当我从数据库加载数据时,pgtypte. text的null字段将被转换为零值,也就是说,它的状态是Undefined.
func GetPerson(){
john := &Person{}
DB.Where("id = ?", "John").First(john) // ID: John, Nickname: NUL
/* john = {
ID: "John",
Age: 30,
Nickname: pgtype.Text{Status: pgtype.Undefined},
}
*/
}
这里,用于保存在DB中的gorm struct 体与从DB加载的gorm struct 体不同是不自然的.
此外,当我修改 struct 的某些字段并再次保存时,由于状态为undefined而出现错误.
func GetAndSave(){
john := &Person{}
DB.Where("id = ?", "John").First(john) // ID: John, Nickname: NUL
/* john = {
ID: "John",
Age: 30,
Nickname: pgtype.Text{Status: pgtype.Undefined},
}
*/
john.Age = 31
DB.Select("*").Update(john) // Error since its nickname has undefined status
}
因此,当我从数据库加载带有null字段的数据时,我希望使pgtype字段自动具有null字段的null状态.我该怎么办?