Home  >  Article  >  Backend Development  >  How to Store Embedded Structs with GORM?

How to Store Embedded Structs with GORM?

DDD
DDDOriginal
2024-11-04 03:09:01841browse

How to Store Embedded Structs with GORM?

Storing Embedded Structs with GORM

When working with GORM and embedded structs, it's essential to understand how GORM handles these structures. For example, consider the following struct:

type A struct {
    point GeoPoint
}

type GeoPoint struct {
    Lat float64
    Lon float64
}

By default, GORM attempts to create a separate table for the embedded struct (GeoPoint), which may not be desirable. To embed the struct as a field within the same table, we need to manually instruct GORM using the column tag.

Solution:

To store an embedded struct as another field, add the gorm:"column:..." tag to the embedded struct field. For instance:

type A struct {
    GORMModel
    Point GeoPoint `gorm:"embedded;column:point"`
}

By setting the embedded option, GORM recognizes the embedded struct and creates a new field named point in the A table. The column option allows us to specify a custom name for the field.

Alternative Solution for JSON Marshalling/Unmarshalling:

This modified solution enables automatic marshalling/unmarshalling of an embedded struct as a JSON column.

type Child struct {
    Lat float64
    Lng float64
}

type ChildArray []Child

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 {
    GORMModel
    Childrens ChildArray `gorm:"column:childrens;type:longtext"`
}

This approach stores the Childrens array as a JSON-encoded string in the childrens column. When retrieving the data, GORM automatically unmarshals the JSON string back into the Childrens array.

The above is the detailed content of How to Store Embedded Structs with GORM?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn