加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql – 如何使用GORM存储嵌入式结构?

发布时间:2020-12-13 16:13:58 所属栏目:百科 来源:网络整理
导读:如果我有这样的类型,如何使用GORM存储嵌入式结构 type A struct { point GeoPoint}type GeoPoint struct { Lat float64 Lon float64} GORM尝试将其添加到新表中,但我想将其添加为另一个字段. 如何才能做到这一点? 我不熟悉Gorm,但是使用sqlx,您需要实现sql.
如果我有这样的类型,如何使用GORM存储嵌入式结构
type A struct {
    point GeoPoint
}

type GeoPoint struct {
    Lat float64
    Lon float64
}

GORM尝试将其添加到新表中,但我想将其添加为另一个字段.

如何才能做到这一点?

我不熟悉Gorm,但是使用sqlx,您需要实现sql.Scanner和sql.Valuer接口,以允许将数据转换为postgres点类型.下面的代码不会检查错误,因此需要进行一些调整.

https://play.golang.org/p/2-Y-wSeAWnj

package main

import (
    "database/sql/driver"
    "fmt"
    "strconv"
    "strings"
)

type GeoPoint struct {
    Lat float64
    Lon float64
}

func (gp GeoPoint) Value() (driver.Value,error) {
    return fmt.Sprintf("(%d,%d)",gp.Lat,gp.Lon),nil
}

func (gp GeoPoint) Scan(src interface{}) error {
    raw := src.(string)
    coords := raw[1 : len(raw)-1]
    vals := strings.Split(coords,",")
    gp.Lat,_ = strconv.ParseFloat(vals[0],64)
    gp.Lon,_ = strconv.ParseFloat(vals[1],64)
    return nil
}

func main() {
    gp := GeoPoint{Lat: 112,Lon: 53}
    d,_ := gp.Value()
    fmt.Printf("%+vn",d)

    gp.Scan("(53,-110)")
    fmt.Printf("%+vn",gp)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读