创建表¶
- 1) 创建对象模型
type User struct {
Id uint `gorm:"primaryKey;autoIncrement"`
Name string
Email *string
Age uint8 `gorm:"defaut:180"`
Birthday *time.Time
MemberNumber sql.NullString
ActivatedAt sql.NullTime
TestBlob []byte
TestClob string `gorm:"type:CLOB"`
CreatedAt time.Time `gorm:"autoCreateTime"`
UpdatedAt time.Time `gorm:"autoUpdateTime"`
}
提示
Id如果写出id,建表的时候会被忽略掉。gorm:"primaryKey;autoIncrement" 表明id字段为主键自增,gorm支持tag,更多使用参考gorm官方文档。
- 2) 数据库中生成对应表
M := db.Migrator()
db.AutoMigrate(&User{})
小技巧
查询数据库中是否有表,用 M.HasTable(&User{})
小技巧
修改表名,用 M.RenameTable(&User{}, "USERS_NEW")
3) BLOB字段类型
TestBlob []byte
4) CLOB字段类型
TestClob string `gorm:"type:CLOB"`