Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store embedded struct with GORM?

Tags:

postgresql

go

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?

like image 215
Javier Manzano Avatar asked Feb 13 '15 15:02

Javier Manzano


2 Answers

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"`
}
like image 131
Muerwre Avatar answered Oct 10 '22 03:10

Muerwre


You can try:

   type A struct {
    point GeoPoint `gorm:"embedded"`
} 
like image 5
Blunt Wang Avatar answered Oct 10 '22 04:10

Blunt Wang