go - 如何在gorm中添加枚举?
问题描述
我正在编写 PostgreSQL 表模式。
type TestTable struct {
ID int `gorm:"column:id;primaryKey;autoIncrement"`
CarType string `gorm:"column:car_type"`
}
那么如何将“SEDAN”、“HATCHBACK”、“MINIVAN”等汽车类型添加为枚举数据类型
解决方案
假设您使用的是 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"
}
推荐阅读
- r - 为什么我的 csv 从 R 导出到 Excel 会在单个单元格中显示一行中的所有内容?
- r - 从 Reddit 抓取,参数的列数不匹配
- winapi - 如何为资源加载 16 位可执行文件 (NE)?
- huawei-mobile-services - 如何在没有谷歌的情况下快速获取 GPS 位置更新 fusedLocationClient
- javascript - 如何从 React 网站计算用户的 CPU 使用百分比?
- javascript - js中对多维数组进行过滤和排序
- arrays - 如何清除数组并用零填充?
- c# - XML 反序列化带回空列表
- r - 合并表列表而不更改标签顺序
- reactjs - React 表排序和搜索