在GORM中的第一次迁移中插入种子数据。

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

Insert seed data at the first time of migration in GORM

问题

我想在AutoMigrate创建数据库表时插入种子数据。

当我执行db.AutoMigrate(&User{})时,它不会返回任何与表创建相关的信息,所以我无法确认表是否已创建、更新或未执行任何操作。

有没有办法从GORM中获取表创建信息以插入种子数据?

这样我就可以像这样插入种子数据:

if err = db.AutoMigrate(&User{}); err != nil {
    if db.CreatedFirstTime {
        //插入种子数据
    }
}
英文:

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
	}
}

答案1

得分: 3

根据文档,你无法从db.AutoMigrate(&User{})中获取表的创建信息。尝试使用Migrator结合查询来获取表的信息。

例如:

if err = db.AutoMigrate(&User{}); err == nil && db.Migrator().HasTable(&User{}) {
    if err := db.First(&User{}).Error; errors.Is(err, gorm.ErrRecordNotFound) {
        //插入种子数据
    }
}
英文:

According to docs, you can't get the table creation information from db.AutoMigrate(&User{}). 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(err, gorm.ErrRecordNotFound) {
        //Insert seed data
    }
}

huangapple
  • 本文由 发表于 2021年9月16日 15:23:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/69204003.html
匿名

发表评论

匿名网友

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

确定