我有一个结构:Documenttype Document struct { ID entity.EntityID Type string ContentType files.MIMEType URL string UploadedByUserID entity.EntityID CreatedAt time.Time}type MIMEType stringconst ( MIMETypeJPG MIMEType = "image/jpeg" MIMETypePDF MIMEType = "application/pdf" MIMETypePNG MIMEType = "image/png" MIMETypeTXT MIMEType = "text/plain")它映射到一个表,其中列的类型为:documentsContentTypevarchar(1024)create table documents( id bigint not null default nextval('documents_id_seq') PRIMARY KEY, url varchar(1024) not null, type varchar(1024) not null, content_type varchar(1024) not null, uploaded_by_user_id bigint, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP not null);Create(&d)其中 是一个实例给我一个错误:dDocument[2.530ms] [rows:1] INSERT INTO "documents" ("type","content_type","url","uploaded_by_user_id","created_at") VALUES ('other_freight','image/png','https://lateralline-documents-dev.s3.us-west-2.amazonaws.com/doc-other_freight-2021_08_25__11_15_13_379569000.png','253608954016301056','2021-08-25 11:15:13.82') RETURNING "id"interface conversion: interface {} is files.MIMEType, not string我想告诉gorm,当我读取和写入字段时,它不仅仅是一个任意字符串,它应该是一个值。有没有办法做到这一点?我在其他 ORM 中也看到了此功能。documents.content_typefiles.MIMEType
1 回答

波斯汪
TA贡献1811条经验 获得超4个赞
您可能需要查看 中的自定义类型(或检查此答案)。go-gorm
简而言之,您需要为结构实现 和 接口。Scanner
Valuer
MIMEType
func (m *MIMEType) Scan(value interface{}) error {
val, ok := value.(string)
if !ok {
return errors.New(fmt.Sprint("Failed to unmarshal string value:", value))
}
*m = MIMEType(val)
return nil
}
func (m MIMEType) Value() (driver.Value, error) {
return string(m), nil
}
- 1 回答
- 0 关注
- 90 浏览
添加回答
举报
0/150
提交
取消