Embedding Structs with GORM
In GORM, when embedding a struct within another, GORM may create a separate table for the embedded struct. However, if you wish to store the embedded struct as an additional field within the main table, the following approach can be utilized:
Solution:
<code class="go">type A struct { Point *GeoPoint } type GeoPoint struct { Lat float64 Lon float64 }</code>
<code class="go">func (gp *GeoPoint) Scan(src interface{}) error { // Convert the `src` value to a byte array. b, ok := src.([]byte) if !ok { return fmt.Errorf("could not convert to byte array") } // Unmarshal the byte array into the `GeoPoint` struct. if err := json.Unmarshal(b, gp); err != nil { return fmt.Errorf("could not unmarshal JSON: %v", err) } return nil } func (gp GeoPoint) Value() (driver.Value, error) { // Marshal the `GeoPoint` struct into a byte array. b, err := json.Marshal(gp) if err != nil { return nil, fmt.Errorf("could not marshal JSON: %v", err) } return string(b), nil }</code>
<code class="go">type A struct { gorm.Model Point *GeoPoint `gorm:"column:point;type:json"` }</code>
By implementing the Scan and Value methods, GORM can convert the embedded struct to and from a JSON format. The gorm:"column" and gorm:"type" tags specify the column name and data type for the embedded struct within the main table.
The above is the detailed content of How do I embed a struct within another struct in GORM and store it as a field in the main table?. For more information, please follow other related articles on the PHP Chinese website!