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

Susan Sarandon
Release: 2024-11-02 22:04:30
Original
803 people have browsed it

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!