- Define an enum type in Go using the
string
type.
type Status string
- Declare constants for each enum value within the defined type.
const (
Pending Status = "Pending"
Approved Status = "Approved"
Rejected Status = "Rejected"
)
- Create a struct that represents the data model where the enum will be used.
type YourModel struct {
// other fields
Status Status
}
- 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'"`
}
- Migrate the model to the database using GORM.
db.AutoMigrate(&YourModel{})
- When creating or updating records, assign enum values using the declared constants.
newRecord := YourModel{
// other field assignments
Status: Approved,
}
db.Create(&newRecord)
- Query records based on the enum value.
var approvedRecords []YourModel
db.Where("status = ?", Approved).Find(&approvedRecords)
- Update enum values in records.
db.Model(&yourRecord).Update("status", Rejected)
- Handle enum values in your application logic based on the declared constants.
if yourRecord.Status == Approved {
// Perform actions for approved records
}