如何编写一个迁移来在 GOLANG 的表字段中添加非空约束。

huangapple go评论76阅读模式
英文:

How to write a migration to add not null in table field GOLANG

问题

我想修改User模型中的一个列。

type User struct {
    gorm.Model
    Email         string `gorm:"unique;type:varchar(50)"`
    Password      string
    Active        bool
    FirstName     string `gorm:"type:varchar(10)"`
    LastName      string `gorm:"type:varchar(10)"`
    Age           int
    Gender        bool   `gorm:"type:boolean"`
    MaritalStatus bool   `gorm:"type:boolean"`
    Address       string `gorm:"type:varchar(10)"`
    City          string `gorm:"type:varchar(10)"`
    State         string `gorm:"type:varchar(10)"`
    Country       string `gorm:"type:varchar(10)"`
    ContactNoOne  string `gorm:"type:varchar(13)"`
    ContactNoTwo  string `gorm:"type:varchar(13)"`
}

我想将Email字段设置为非空。如何编写迁移来实现这个目标?

英文:

I want to alter a column in User Model

type User struct {
	gorm.Model
	Email         string `gorm:"unique;type:varchar(50)"`
	Password      string
	Active        bool
	FirstName     string `gorm:"type:varchar(10)"`
	LastName      string `gorm:"type:varchar(10)"`
	Age           int
	Gender        bool   `gorm:"type:boolean"`
	MaritalStatus bool   `gorm:"type:boolean"`
	Address       string `gorm:"type:varchar(10)"`
	City          string `gorm:"type:varchar(10)"`
	State         string `gorm:"type:varchar(10)"`
	Country       string `gorm:"type:varchar(10)"`
	ContactNoOne  string `gorm:"type:varchar(13)"`
	ContactNoTwo  string `gorm:"type:varchar(13)"`
}

I want to make Email field as not nullable. How to write migration for that?

答案1

得分: 1

在标签gorm上添加not null

type User struct {
    ...
    Email         string `gorm:"unique;type:varchar(50);not null"`
    ...
}

文档:https://gorm.io/docs/models.html

英文:

add not null on tag gorm

type User struct {
    ...
    Email         string `gorm:"unique;type:varchar(50);not null"`
    ...
}

doc : https://gorm.io/docs/models.html

答案2

得分: 0

编辑你的模型,然后使用AutoMigrate函数。

db.AutoMigrate(&User{})

文档:https://gorm.io/docs/migration.html

英文:

Edit your model, then us AutoMigrate

db.AutoMigrate(&User{})

Documentation: https://gorm.io/docs/migration.html

huangapple
  • 本文由 发表于 2022年5月17日 12:20:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/72268177.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定