英文:
how to define start value for GORM auto increment
问题
我正在使用gorm在我的项目中,并且我需要为其自增功能设置一个起始值。
我尝试添加了这行代码,但没有进展:
type User struct {
gorm.Model
ID uint `gorm:"primarykey;autoIncrement:100"`
Email string `gorm:"not null; unique" form:"email" binding:"required"`
}
如何为gorm的AutoIncrement函数定义一个起始值,比如100?
英文:
I'm using gorm in my project, and I need to set a started value for its auto-increment function.
I tried adding this line, but no progress:
type User struct {
gorm.Model
ID uint `gorm:"primarykey;autoIncrement:100"`
Email string `gorm:"not null; unique" form:"email" binding:"required"`
}
How can I define a starter value like 100 for the gorm AutoIncrement function?
答案1
得分: 1
我不认为你可以直接使用gorm来完成这个操作。虽然有点繁琐,但你可以在AutoMigrate之后执行原始的SQL查询来设置自增值:
SELECT GREATEST(100, MAX(id) + 1) FROM table_name INTO @autoinc;
ALTER TABLE table_name AUTO_INCREMENT = @autoinc;
这样可以确保该值最小为100(如果表中没有行),或者如果已经存在行,则为下一个值。
英文:
I don't think, you can do it natively with gorm. It's a bit hacky, but you could execute a raw SQL query after your AutoMigrate to set the increment value:
SELECT GREATEST(100, MAX(id) + 1) FROM table_name INTO @autoinc;
ALTER TABLE table_name AUTO_INCREMENT = @autoinc;
This way you make sure, the value is minimum 100 (if there are no rows in the table), or it is the next value if there are rows already.
答案2
得分: 0
我找到了一个解决方案。在你的自动迁移代码之后,你可以写下这段代码:
DB.Create(
<你的表模型>{
ID: <起始值>,
DeletedAt: gorm.DeletedAt{Time: time.Now(), Valid: true}}
)
请注意,这是一个示例代码,你需要将 <your_table_model>
替换为你的表模型名称,将 <start_value>
替换为起始值。
英文:
I find a solution. after your automigrate code , you can write this code:
DB.Create(
<your_table_model>{
ID: <start_value>,
DeletedAt: gorm.DeletedAt{Time: time.Now(), Valid: true}}
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论