Home > OS >  how to define start value for GORM auto increment
how to define start value for GORM auto increment

Time:09-30

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?

CodePudding user response:

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.

  • Related