Home >Backend Development >Golang >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!