英文:
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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论