亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將接口設置為具有許多使用 GORM 的實現的屬性

將接口設置為具有許多使用 GORM 的實現的屬性

Go
海綿寶寶撒 2022-09-12 21:01:07
我有一個后記數據庫,它將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)

}


查看完整回答
反對 回復 2022-09-12
  • 1 回答
  • 0 關注
  • 101 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號