AutoMigration()方法不会添加NOT NULL属性,但可以通过手动添加Tag实现。示例代码如下:
type User struct {
ID uint gorm:"primaryKey"
Name string gorm:"not null"
Age int
CreatedAt time.Time
UpdatedAt time.Time
}
// 添加Tag
type UserMigration struct {
Name string gorm:"not null"
Age int
}
err := db.AutoMigrate(&User{})
if err != nil { panic(err) }
// 检查是否添加了NOT NULL属性 if db.Migrator().HasColumn(&UserMigration{}, "name") { fmt.Println("name column has not null attribute") } else { fmt.Println("name column does not have not null attribute") }