SecureCRT/SecureFX 8.3 中文乱码双端排查:3步配置与1个配置文件修改
2026/7/12 7:26:25
GORM 使用 struct tag 定义字段行为:
type User struct { FieldName DataType `gorm:"tag1:value1;tag2:value2" json:"field_name"` }优先级(从高到低):
gorm:"..."主控制标签(数据库行为)
其他标签(json、form 等)
结构体字段名作为默认列名(SnakeCase)
gorm:"column:user_name"gorm:"type:varchar(100)"gorm:"primaryKey"与 primaryKey 组合常用。
gorm:"primaryKey;autoIncrement"gorm:"unique" // 单字段唯一 gorm:"uniqueIndex" // 创建唯一索引 gorm:"uniqueIndex:idx_name" // 复合唯一索引gorm:"index" // 单字段索引 gorm:"index:idx_name" // 指定索引名 gorm:"index:idx_name,priority:1" // 复合索引顺序gorm:"size:255"gorm:"default:0" gorm:"default:'unknown'"gorm:"not null"控制 GORM 是否对该字段进行写入或读取:
gorm:"<-:create" // 仅创建时写入 gorm:"<-:update" // 仅更新时写入 gorm:"<-:false" // 禁止写入 gorm:"->:false" // 查询不读该字段 gorm:"-:" // 读写都禁用 gorm:"-" // 完全忽略该字段gorm:"autoCreateTime" gorm:"autoCreateTime:milli" // 毫秒 gorm:"autoCreateTime:nano" // 纳秒gorm:"autoUpdateTime" gorm:"autoUpdateTime:milli" gorm:"autoUpdateTime:nano"gorm:"foreignKey:UserID"gorm:"references:ID"gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"gorm:"many2many:user_roles"gorm:"polymorphic:Owner"适用于 JSON、MsgPack 等类型存储。
gorm:"serializer:json"type User struct { Hobbies []string `gorm:"serializer:json"` }gorm:"embedded"gorm:"embeddedPrefix:user_"gorm:"comment:'用户年龄'"下面是一个实际业务级别的模型,涵盖各种标签。
type User struct { ID uint `gorm:"primaryKey;autoIncrement;comment:'主键ID'"` UserName string `gorm:"column:user_name;type:varchar(50);uniqueIndex;not null;comment:'用户名'"` Email string `gorm:"type:varchar(100);index:idx_email;not null;comment:'邮箱地址'"` Age int `gorm:"default:0;comment:'年龄'"` Profile UserProfile `gorm:"embedded;embeddedPrefix:profile_"` Tags []string `gorm:"serializer:json;comment:'标签(JSON)'"` CreatedAt time.Time `gorm:"autoCreateTime"` UpdatedAt time.Time `gorm:"autoUpdateTime"` DeletedAt gorm.DeletedAt `gorm:"index"` } type UserProfile struct { Address string `gorm:"type:varchar(200)"` Avatar string `gorm:"type:varchar(255)"` }type User struct { ID uint Orders []Order `gorm:"foreignKey:UserID"` } type Order struct { ID uint UserID uint }type User struct { ID uint Roles []Role `gorm:"many2many:user_roles"` } type Role struct { ID uint Name string }如果字段是 0 或 "",GORM 不会主动应用 default。
解决方法:
Age *int `gorm:"default:18"`not null时,GORM 不会自动加默认非空| 标签 | 作用 |
|---|---|
| column | 指定列名 |
| type | 指定数据库类型 |
| primaryKey | 主键 |
| autoIncrement | 自增 |
| unique / uniqueIndex | 唯一约束 |
| index | 索引 |
| size | 字符串长度 |
| default | 默认值 |
| not null | 非空 |
| <- | 写属性 |
| -> | 读属性 |
| - | 忽略字段 |
| autoCreateTime | 创建时间 |
| autoUpdateTime | 更新时间 |
| foreignKey | 外键字段 |
| references | 外键关联字段 |
| many2many | 多对多 |
| serializer:json | JSON 存储 |
| embedded | 内嵌字段 |
| embeddedPrefix | 内嵌字段前缀 |
| comment | 字段注释 |