2

I have a database query that returns an extra calculated column along with all the mapped struct columns. I want to map it back into the struct while also being able to extract the calculated column which is not part of the struct. I can get everything by using the xorm QueryInterface() function, but I can't seem to find how I can convert the resulting map[string]interface{} back into the struct...

Any idea? I saw gorm has db.Model(...).Create(...) but can't seem to find the equivalent in xorm.

Christopher
  • 412
  • 3
  • 11

1 Answers1

0

Well, I found a solution, though not an elegant one, I wish there was something better, so if someone else has a good answer...

I basically just decided to use JSON Marshal then Unmarshal to take the map[string]interface{} and turn it back into the struct. This means I had to use a bunch of json:"..." tags on the struct, as the column->property mapping differed from those used by xorm. Kinda ugly but it allowed me to capture the extra props from the database query.

type MyStruct struct {
    ID                   int64              `xorm:"primaryKey"`
    ProductID            int64              `xorm:"INDEX" json:"product_id"`
    Index                int64              `xorm:"INDEX NOT NULL DEFAULT 0"`
    Code                 string             `xorm:"-" json:"code"`
}

func (b *MyDBStruct) FromMap(src map[string]interface{}) error {
    jsonStr, _ := json.Marshal(src)
    err := json.Unmarshal(jsonStr, &b)
    if err == nil {
        for key := range src {
            b.AfterSet(key, nil)
        }
    }
    return err
}
Christopher
  • 412
  • 3
  • 11