You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 14:37:41