我有 struct ,那是表的模型.一切都很好,直到我想向其中添加类型 struct 并将其序列化为json(位置).

type Dome struct {
    gorm.Model
    Location Location `json:"location" gorm:"serializer:json"`
    Title    string   `json:"title" gorm:"type:varchar(100)"`
}

type Location struct {
    X1 int
    Y1 int
    X2 int
    Y2 int
}

执行.Update()时,这些值被序列化并保存到Column中.但在执行创建或保存时,它会抛出错误

sql: converting argument $ type: unsupported type Location, a struct

据我所知,GORM已经有一些默认的序列化程序,比如json.它似乎在更新上起作用,但在任何创建上都不起作用.此外,在调试时,我看到这些值被反序列化,并在 struct 中再次出现.

我找不到答案,我错过了什么,也许需要补充一些其他的东西,但我没有那么有经验.如何使用GORM将Struct序列化为列?

推荐答案

package main

import (
    "fmt"
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

type Dome struct {
    gorm.Model
    Location Location `json:"location" gorm:"serializer:json"`
    Title    string   `json:"title" gorm:"type:varchar(100)"`
}

type Location struct {
    X1 int
    Y1 int
    X2 int
    Y2 int
}

func main() {
    db, _ := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})

    /*err := db.AutoMigrate(&Dome{})
    if err != nil {
        return
    }*/

        l := Location{}
        l.Y1 = 1
        l.X1 = 2
        l.X2 = 3
        l.Y2 = 4

        d := Dome{}
        d.Title = "test"
        d.Location = l
        db.Create(&d)

        d.Location.Y2 = 6
        db.Save(&d)

        d.Location.X2 = 4
        db.Updates(&d)

    _target := []*Dome{}
    db.Find(&_target)
    for _, t := range _target {
        fmt.Printf("%+v \n", t)
    }
}

我try 了这种方式和序列化程序:JSON工作起来没有任何问题.

输出:

&{Model:{ID:1 CreatedAt:2022-08-06 14:39:59.184012808 +0530 +0530 UpdatedAt:2022-08-06 14:39:59.184012808 +0530 +0530 DeletedAt:{Time:0001-01-01 00:00:00 +0000 UTC Valid:false}} Location:{X1:2 Y1:1 X2:3 Y2:4} Title:test} 
&{Model:{ID:2 CreatedAt:2022-08-06 14:40:55.666162544 +0530 +0530 UpdatedAt:2022-08-06 14:40:55.677998201 +0530 +0530 DeletedAt:{Time:0001-01-01 00:00:00 +0000 UTC Valid:false}} Location:{X1:2 Y1:1 X2:3 Y2:6} Title:test} 
&{Model:{ID:3 CreatedAt:2022-08-06 14:41:29.361814733 +0530 +0530 UpdatedAt:2022-08-06 14:41:29.367237119 +0530 +0530 DeletedAt:{Time:0001-01-01 00:00:00 +0000 UTC Valid:false}} Location:{X1:2 Y1:1 X2:4 Y2:6} Title:test} 

enter image description here

根据文档,您可以注册序列化程序并实现如何序列化和反序列化数据. https://gorm.io/docs/serializer.html#Register-Serializer

Go相关问答推荐

Golang使用Run()执行的命令没有返回

错误&对象已被Golang在K8s操作符上修改

为什么要立即调用内联函数,而不仅仅是调用其包含的函数?

使用 goroutine 比较 Golang 中的两棵树是等价的

命令行参数在 Golang 程序中不正确地接受为参数

使用 LINQ 对内部数组进行排序

Golang 中的泛型类型转换

我在 go 中制作的递归函数有什么问题?

Go:从 ssl 证书中获取 'subject/unstructeredName' 的值

使用 GO 在侧 tar 文件中提取 tar 文件的最快方法

Golang prometheus 显示自定义指标

Golang 数据库/sql 与 SetMaxOpenConns 挂起

将未知长度切片的值分配给Go中的 struct ?

golang jwt.MapClaims 获取用户ID

在 Golang 中使用 OR 条件验证 struct 的两个字段

Golang API 的 HTTPS

无法识别同步错误.使用一次

使用不安全的指针从 [] 字符串中获取值

Go:如何通过 GIN-Router 从 AWS S3 将文件作为二进制流发送到浏览器?

关于GO的几个问题