Home >Backend Development >Golang >How to Store Embedded Structs in GORM as a Single Entity?

How to Store Embedded Structs in GORM as a Single Entity?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 22:04:30942browse

How to Store Embedded Structs in GORM as a Single Entity?

Incorporating Embedded Structs in GORM

Storing embedded structs with GORM poses a challenge when dealing with types such as:

<code class="go">type A struct {
    point GeoPoint
}

type GeoPoint struct {
    Lat float64
    Lon float64
}</code>

By default, GORM attempts to create a separate table for the embedded struct GeoPoint. However, to add it as a field within the parent struct A, consider the following solution inspired by the insights of Chris:

<code class="go">import (
    "encoding/json"

    "gorm.io/gorm"
)

// Define custom Scan and Value methods for ChildArray to enable automatic marshalling and unmarshalling.
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
}

// Define the parent struct with the embedded ChildArray.
type Parent struct {
    *gorm.Model
    Childrens ChildArray `gorm:"column:childrens;type:longtext"`
}</code>

This approach allows for seamless marshalling and unmarshalling of the embedded struct within the parent struct, ensuring it is stored and retrieved from the database as a single entity.

The above is the detailed content of How to Store Embedded Structs in GORM as a Single Entity?. 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