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

How to Store Embedded Structs with GORM?

DDD
Release: 2024-11-04 03:09:01
Original
933 people have browsed it

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
}
Copy after login

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"`
}
Copy after login

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"`
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template