使用GORM插入MySQL时JSON字段user始终为NULL,求解决方法
解决GORM插入MySQL时JSON字段为NULL的问题
问题根源
- 结构体字段仅配置了
json标签,GORM默认依赖gorm标签映射数据库列,无法识别json标签关联user字段。 - 代码存在变量名错误:误操作类型
Profile而非实例profile,且引用了未定义的User类型(实际应为UserInfo)。 - 未明确告知GORM需将
UserInfo结构体序列化为JSON存入数据库字段。
修正方案
1. 为结构体添加GORM标签
type UserInfo struct { Name string `json:"name"` Age int `json:"age"` } type Profile struct { ID string `json:"id" gorm:"column:id;primaryKey"` User *UserInfo `json:"user" gorm:"column:user;type:json"` UserType string `json:"user_type" gorm:"column:user_type"` }
通过gorm:"column:xxx"指定数据库列名,type:json明确字段类型,让GORM知晓需要将结构体序列化为JSON字符串存储。
2. 修正插入代码的变量和类型错误
var profile Profile profile.ID = "Demo~1" profile.UserType = "Permanent" profile.User = &UserInfo{ Name: "John", Age: 24, } if err := db.Create(&profile).Error; err != nil { fmt.Printf("插入失败: %v\n", err) }
确保操作的是profile实例而非Profile类型,同时使用正确的UserInfo结构体类型。
说明
修正后,GORM会自动将*UserInfo结构体序列化为JSON格式字符串,存入MySQL的user字段中,解决字段为NULL的问题。
内容的提问来源于stack exchange,提问作者pip
相关产品推荐
相关产品推荐

