embedding structs with gorm
を埋め込みます。ただし、メインテーブル内の追加フィールドとして埋め込まれた構造体を保存する場合、次のアプローチを利用できます:
ソリューション:
type A struct {
Point *GeoPoint
}
type GeoPoint struct {
Lat float64
Lon float64
}
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
}
type A struct {
gorm.Model
Point *GeoPoint `gorm:"column:point;type:json"`
}
スキャンと値のメソッドを実装することにより、Gormは埋め込み構造体をJSON形式に変換できます。ゴーム:「列」とゴーム:「タイプ」タグは、メインテーブル内に埋め込まれた構造体の列名とデータ型を指定します。 免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3