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

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

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

问题

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

  1. type User struct {
  2. gorm.Model
  3. Email string `gorm:"unique;type:varchar(50)"`
  4. Password string
  5. Active bool
  6. FirstName string `gorm:"type:varchar(10)"`
  7. LastName string `gorm:"type:varchar(10)"`
  8. Age int
  9. Gender bool `gorm:"type:boolean"`
  10. MaritalStatus bool `gorm:"type:boolean"`
  11. Address string `gorm:"type:varchar(10)"`
  12. City string `gorm:"type:varchar(10)"`
  13. State string `gorm:"type:varchar(10)"`
  14. Country string `gorm:"type:varchar(10)"`
  15. ContactNoOne string `gorm:"type:varchar(13)"`
  16. ContactNoTwo string `gorm:"type:varchar(13)"`
  17. }

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

英文:

I want to alter a column in User Model

  1. type User struct {
  2. gorm.Model
  3. Email string `gorm:"unique;type:varchar(50)"`
  4. Password string
  5. Active bool
  6. FirstName string `gorm:"type:varchar(10)"`
  7. LastName string `gorm:"type:varchar(10)"`
  8. Age int
  9. Gender bool `gorm:"type:boolean"`
  10. MaritalStatus bool `gorm:"type:boolean"`
  11. Address string `gorm:"type:varchar(10)"`
  12. City string `gorm:"type:varchar(10)"`
  13. State string `gorm:"type:varchar(10)"`
  14. Country string `gorm:"type:varchar(10)"`
  15. ContactNoOne string `gorm:"type:varchar(13)"`
  16. ContactNoTwo string `gorm:"type:varchar(13)"`
  17. }

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

答案1

得分: 1

在标签gorm上添加not null

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

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

英文:

add not null on tag gorm

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

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

答案2

得分: 0

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

  1. db.AutoMigrate(&User{})

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

英文:

Edit your model, then us AutoMigrate

  1. 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:

确定