I want to insert seed data when AutoMigrate
creates a table in the database.
When I execute db.AutoMigrate(&User{})
, it doesn't return any information related to the table creation, so I can't confirm that table has been created, updated, or doesn't do anything.
Is there any way to know the table creation information from GORM to insert seed data?
So that I can insert seed data like:
if err = db.AutoMigrate(&User{}); err != nil {
if db.CreatedFirstTime {
//Insert seed data
}
}
CodePudding user response:
According to docs, you can't get the table creation information from db.AutoMigrate(&User{})
.
You can try to use Migrator
with queries combination to get table's info.
For example:
if err = db.AutoMigrate(&User{}); err == nil && db.Migrator().HasTable(&User{}){
if err := db.First(& User{}).Error; errors.Is(gorm.ErrRecordNotFound, err) {
//Insert seed data
}
}