gorm enum

  1. Define an enum type in Go using the string type.
type Status string
  1. Declare constants for each enum value within the defined type.
const (
    Pending   Status = "Pending"
    Approved  Status = "Approved"
    Rejected  Status = "Rejected"
)
  1. Create a struct that represents the data model where the enum will be used.
type YourModel struct {
    // other fields
    Status Status
}
  1. Use GORM tags to specify the enum field type and constraints in the database.
type YourModel struct {
    // other fields
    Status Status `gorm:"type:enum('Pending', 'Approved', 'Rejected');default:'Pending'"`
}
  1. Migrate the model to the database using GORM.
db.AutoMigrate(&YourModel{})
  1. When creating or updating records, assign enum values using the declared constants.
newRecord := YourModel{
    // other field assignments
    Status: Approved,
}

db.Create(&newRecord)
  1. Query records based on the enum value.
var approvedRecords []YourModel
db.Where("status = ?", Approved).Find(&approvedRecords)
  1. Update enum values in records.
db.Model(&yourRecord).Update("status", Rejected)
  1. Handle enum values in your application logic based on the declared constants.
if yourRecord.Status == Approved {
    // Perform actions for approved records
}