Home > Backend Development > Golang > How do I embed a struct within another struct in GORM and store it as a field in the main table?

How do I embed a struct within another struct in GORM and store it as a field in the main table?

Barbara Streisand
Release: 2024-11-03 03:20:03
Original
1042 people have browsed it

How do I embed a struct within another struct in GORM and store it as a field in the main table?

Embedding Structs with GORM

In GORM, when embedding a struct within another, GORM may create a separate table for the embedded struct. However, if you wish to store the embedded struct as an additional field within the main table, the following approach can be utilized:

Solution:

  1. Define an embedded struct:
<code class="go">type A struct {
    Point *GeoPoint
}

type GeoPoint struct {
    Lat float64
    Lon float64
}</code>
Copy after login
  1. Implement the sql.Scanner and driver.Valuer interfaces for the embedded struct:
<code class="go">func (gp *GeoPoint) Scan(src interface{}) error {

    // Convert the `src` value to a byte array.
    b, ok := src.([]byte)
    if !ok {
        return fmt.Errorf("could not convert to byte array")
    }

    // Unmarshal the byte array into the `GeoPoint` struct.
    if err := json.Unmarshal(b, gp); err != nil {
        return fmt.Errorf("could not unmarshal JSON: %v", err)
    }

    return nil
}

func (gp GeoPoint) Value() (driver.Value, error) {

    // Marshal the `GeoPoint` struct into a byte array.
    b, err := json.Marshal(gp)
    if err != nil {
        return nil, fmt.Errorf("could not marshal JSON: %v", err)
    }

    return string(b), nil
}</code>
Copy after login
  1. Update the GORM model to use the embedded struct with the gorm:"column" and gorm:"type" tags:
<code class="go">type A struct {
    gorm.Model
    Point *GeoPoint `gorm:"column:point;type:json"`
}</code>
Copy after login

By implementing the Scan and Value methods, GORM can convert the embedded struct to and from a JSON format. The gorm:"column" and gorm:"type" tags specify the column name and data type for the embedded struct within the main table.

The above is the detailed content of How do I embed a struct within another struct in GORM and store it as a field in the main table?. 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