Assuming you are using GORM with PostgreSQL. First in your database create a type.
CREATE TYPE car_type AS ENUM (
'SEDAN',
'HATCHBACK',
'MINIVAN');
Then you will need to define the following model:
import "database/sql/driver"
type carType string
const (
SEDAN carType = "SEDAN"
HATCHBACK carType = "HATCHBACK"
MINIVAN carType = "MINIVAN"
)
func (ct *carType) Scan(value interface{}) error {
*ct = carType(value.([]byte))
return nil
}
func (ct carType) Value() (driver.Value, error) {
return string(ct), nil
}
type MyTable struct {
gorm.Model
CarType carType `gorm:"type:car_type"`
}
func (MyTable) TableName() string {
return "my_table"
}
Note for MySQL users, you can add struct tag gorm:
or sql:
so you don't have to run raw query to create enum in the database.
CarType carType `gorm:"type:enum('SEDAN', 'HATCHBACK', 'MINIVAN')";"column:car_type"`
OR
CarType carType `sql:"type:ENUM('SEDAN', 'HATCHBACK', 'MINIVAN')" gorm:"column:car_type"`