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

994 views Asked by At

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?

2

There are 2 answers

0
Rahmat Fathoni On

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

0
Benoît Zu On

Edit your model, then us AutoMigrate

db.AutoMigrate(&User{})

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