利用 GORM 将属性设置为具有多种实现的接口
时间:2024-02-26
浏览:325
作者:佚名
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《利用 GORM 将属性设置为具有多种实现的接口》,聊聊,希望可以帮助到正在努力赚钱的你。
问题内容
我有一个 postgres 数据库,它将 json 存储为其字段之一。表的结构为:
type table struct {
id int
vehicletype string
vehicle vehicle `gorm:"type:jsonb"`
// ......
}
现在,车辆是一个接口
type vehicle interface {
getenginemodel() string
}
它有很多实现,我将分享其中之一 - car
type car struct {
carenginemodel string //the attributes will be different for different
//implementation
}
func (car car) getenginemodel() string {
return car.carenginemodel
}
为了解析特定结构(即汽车、自行车等)中的属性,我可以实现所有实现的 scan 和 value 接口,如下所示:-
func (car *Car) Scan(value interface{}) error {
//Want to use this implementation of Scan based on VehicleType
//attribute of struct table
b, ok := value.([]byte)
if !ok {
return errors.New("type assertion to []byte failed")
}
*car = json.Unmarshal(b, &car)
}
有没有办法根据其他表列判断要使用哪种 scan 实现,或者使用 gorm 执行相同操作的替代方法?我只想要一张表(遗传 json 类型),因此不想使用多态关联将不同的表用于不同的实现。
正确答案
您可以添加一个单独的字段来保存原始 json 数据,然后实现 gorm 特定挂钩来编组/解组该数据。
type Table struct {
ID int
VehicleType string
Vehicle Vehicle `gorm:"-"`
// ...
VehicleRaw []byte `gorm:"column:vehicle"`
}
func (t *Table) BeforeSave(tx *gorm.DB) (err error) {
raw, err := json.Marshal(t.Vehicle)
if err != nil {
return err
}
t.VehicleRaw = raw
return nil
}
func (t *Table) AfterFind(tx *gorm.DB) (err error) {
switch t.VehicleType {
case "CAR":
t.Vehicle = &Car{}
case "BIKE":
t.Vehicle = &Bike{}
}
return json.Unmarshal(t.VehicleRaw, t.Vehicle)
}
本篇关于《利用 GORM 将属性设置为具有多种实现的接口》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.30
11.30
11.30
11.30
11.30
11.30
11.30
热门专题
