Home  >  Article  >  Backend Development  >  How to Store Embedded Structs in GORM within the Same Table as the Parent Struct?

How to Store Embedded Structs in GORM within the Same Table as the Parent Struct?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-03 06:08:02723browse

How to Store Embedded Structs in GORM within the Same Table as the Parent Struct?

Embedding Structs in GORM for Data Storage

In GORM, handling embedded structs can be a challenge when you want to store the nested struct within the same table as the parent struct. By default, GORM assumes embedded structs as separate entities and attempts to create a new table for them. However, you may prefer to include the embedded struct as an additional field within the parent struct's table.

Solution

One effective solution involves implementing the Scan() and Value() methods for a custom type that represents the embedded struct array. These methods allow GORM to serialize and deserialize the embedded struct to and from JSON, enabling seamless storage and retrieval.

For illustration, consider the following example:

<code class="go">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
}</code>

Here, the ChildArray custom type represents the embedded array of Child structs. It implements the Scan() and Value() methods to handle JSON serialization and deserialization.

To embed and store the ChildArray in the Parent struct, you can define the model as follows:

<code class="go">type Parent struct {
    *gorm.Model
    Childrens ChildArray `gorm:"column:childrens;type:longtext"`
}</code>

With this configuration, GORM recognizes the Childrens field as a custom type and automatically serializes and deserializes the embedded Child structs to and from JSON when interacting with the database.

The above is the detailed content of How to Store Embedded Structs in GORM within the Same Table as the Parent Struct?. 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