登录
首页 >  Golang >  Go问答

将结构序列化时 Gorm 的保存/创建

来源:stackoverflow

时间:2024-03-19 17:54:31 250浏览 收藏

在使用 Gorm 将结构序列化到数据库列时,遇到创建或保存时出现错误。这是因为 Gorm 的默认序列化程序不适用于嵌套结构。解决方法是注册自定义序列化程序,定义如何序列化和反序列化数据。

问题内容

我有结构,即表的模型。一切都很好,直到我想向其中添加类型结构并将其序列化为 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
}

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

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

据我了解,gorm 已经有一些默认的序列化程序,例如 json。它似乎适用于更新,但不适用于任何创建。此外,在调试时,我看到这些值被反序列化并再次出现在结构中。

我找不到答案,我缺少什么,也许需要添加其他东西,但我经验不足。如何使用 gorm 将结构序列化为列?


正确答案


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)
    }
}

我尝试了这种方式,并且 serializer: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}

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

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>