This short post is part of my coding session, where I review the usage of ID and KEY (UUID) fields for my research project. In particular, I will remove the ID fields’ usage and check if the system works as expected.
How to remove the GORM ID field?
Here is an example of Model transofrmation.
Initial version:
type URLImage struct {
gorm.Model
URL string `gorm:"unique_index:idx_url;not null;size:255"`
ImageURL string `gorm:"unique_index:idx_url;not null;size:255"`
ImageTitle string `gorm:"size:255"`
}
By embedding gorm.Model, GORM will automatically generate four fields: ID, CreatedAt, UpdatedAt, DeletedAt. Here is the source code from GORM package:
// Model base model definition, including fields `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`, which could be embedded in your models
// type User struct {
// gorm.Model
// }
type Model struct {
ID uint `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index"`
}
To stop generating the ID field, we can remove the model and delete the ID field from our model.
Transformed version:
type URLImage struct {
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index"`
URL string `gorm:"unique_index:idx_url;not null;size:255"`
ImageURL string `gorm:"unique_index:idx_url;not null;size:255"`
ImageTitle string `gorm:"size:255"`
}
Model without ID primary key.
By doing this, we stop generating the ID primary key. Also, GORM will still auto-populate CreatedAt, UpdatedAt, DeletedAt columns.