首页 > 解决方案 > 如何在gorm中添加枚举?

问题描述

我正在编写 PostgreSQL 表模式。

type TestTable struct {
    ID        int    `gorm:"column:id;primaryKey;autoIncrement"`
    CarType   string `gorm:"column:car_type"`
}

那么如何将“SEDAN”、“HATCHBACK”、“MINIVAN”等汽车类型添加为枚举数据类型

标签: gogo-gorm

解决方案


假设您使用的是 GORM。首先在您的数据库中创建一个类型。

CREATE TYPE car_type AS ENUM (
    'SEDAN',
    'HATCHBACK',
    'MINIVAN');

然后,您将需要定义以下模型:

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 `sql:"car_type"`
}

func (MyTable) TableName() string {
    return "my_table"
}

推荐阅读