How can I store an embedded struct with GORM if I have a type like this
type A struct {
point GeoPoint
}
type GeoPoint struct {
Lat float64
Lon float64
}
GORM tries to add it in a new table, but I want to add it as another field.
How can this be done?
For anyone, who's searching the way to put struct inside GORM model and make it marshalling and unmarshalling automatically.
This solution is based on chris's answer. And it works!
For example, I want to put array of Childrens inside Parent as marshalled JSON:
type Child struct {
Lat float64
Lng float64
}
type ChildArray []Children
func (sla *ChildArray) Scan(src interface{}) error {
return json.Unmarshal(src.([]byte), &sla)
}
func (sla ChildArray) Value() (driver.Value, error) {
val, err := json.Marshal(sla)
return string(val), err
}
type Parent struct {
*gorm.Model
Childrens ChildArray `gorm:"column:childrens;type:longtext"`
}
You can try:
type A struct {
point GeoPoint `gorm:"embedded"`
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With