登录
首页 >  Golang >  Go问答

在 gorm 中使用枚举类型进行数据库字段映射

来源:stackoverflow

时间:2024-03-02 18:57:24 414浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《在 gorm 中使用枚举类型进行数据库字段映射》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我正在编写 postgresql 表架构。

775576​​644216

那么我如何添加“sedan”、“hatchback”、“minivan”等汽车类型作为枚举数据类型


正确答案


假设您将 gorm 与 postgresql 一起使用。首先在数据库中创建一个类型。

create type car_type as enum (
    'sedan',
    'hatchback',
    'minivan');

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

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"
}

mysql 用户请注意,您可以添加结构标记 gorm:sql:,这样您就不必运行原始查询来在数据库中创建枚举。

cartype cartype `gorm:"type:enum('sedan', 'hatchback', 'minivan')";"column:car_type"`

或者

cartype cartype `sql:"type:enum('sedan', 'hatchback', 'minivan')" gorm:"column:car_type"`

为了扩展尼克的答案,我添加以下内容以实现自动化:

假设您有 dbclient 结构,您可以创建一个方法来创建此汽车类型:

func (psqlClient *DBClient) CreateCarTypeEnum() error {
    result := psqlClient.db.Exec("SELECT 1 FROM pg_type WHERE typname = 'car_type';")

    switch {
    case result.RowsAffected == 0:
        if err := psqlClient.db.Exec("CREATE TYPE car_type AS ENUM ('SEDAN', 'HATCHBACK', 'MINIVAN');").Error; err != nil {
            log.Error().Err(err).Msg("Error creating car_type ENUM")
            return err
        }

        return nil
    case result.Error != nil:
        return result.Error

    default:
        return nil
    }
}

本篇关于《在 gorm 中使用枚举类型进行数据库字段映射》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>