我有一個后記數據庫,它將JSON存儲為其字段之一。該表的結構為:type Table struct { ID int VehicleType string Vehicle Vehicle `gorm:"type:jsonb"`// ...... }現在,車輛是一個界面type Vehicle interface { GetEngineModel() string}它有很多實現,我將分享其中之一 - 汽車type Car struct { CarEngineModel string //the attributes will be different for different //implementation}func (car Car) GetEngineModel() string { return car.CarEngineModel}為了解析特定結構(即汽車,自行車,..)中的屬性,我可以實現所有實現的掃描和值接口,如下所示:-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)}有沒有辦法根據其他表列來判斷要使用哪種掃描實現,或者使用GORM的另一種方法來做同樣的事情?我只想要一個表(遺傳json類型),所以不想使用不同的表來使用多態關聯的不同實現。去戈姆
1 回答

猛跑小豬
TA貢獻1858條經驗 獲得超8個贊
您可以添加一個單獨的字段來保存原始 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)
}
- 1 回答
- 0 關注
- 101 瀏覽
添加回答
舉報
0/150
提交
取消