登录
首页 >  Golang >  Go问答

如何在golang中使用GORM框架将结构数组嵌入到另一个结构中并将其保存在数据库中

来源:stackoverflow

时间:2024-04-12 14:39:41 480浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《如何在golang中使用GORM框架将结构数组嵌入到另一个结构中并将其保存在数据库中》,涉及到,有需要的可以收藏一下

问题内容

type dlinformation struct {
    base64encodedimage string `json:"base64_encoded_image"`
    licenseno          string `json:"license_no" gorm:"type:varchar(25)"`
    licensenumber      string `json:"license_number" gorm:"primarykey;type:varchar(25)"`
    name               string `json:"name" gorm:"type:varchar(30);not null"`
    fathername         string `json:"father_name" gorm:"type:varchar(30)"`
    dob                string `json:"dob" gorm:"type:varchar(30)"`
    bloodgroup         string `json:"blood_group" gorm:"type:varchar(20)"`
    gender             string `json:"gender" gorm:"type:varchar(10)"`
    status             string `json:"status" gorm:"type:varchar(40)"`
    rto                string `json:"rto" gorm:"type:varchar(30)"`
    presentaddress     string `json:"present_address" gorm:"type:varchar(60)"`
    state              string `json:"state" gorm:"type:varchar(30)"`
    //licenses           []license `json:"licenses" gorm:"references:licenseid;constraint:ondelete:cascade"`
    licenses []license `json:"licenses" gorm:"embedded"`
    vehicles []vehicle `json:"vehicles" gorm:"embedded"`
    //vehicles           []vehicle `json:"vehicles" gorm:"references:vehicleid;constraint:ondelete:cascade"`
}


type license struct {
    licensetype string `json:"license_type"`
    issuedate   string `json:"issue_date"`
    expirydate  string `json:"expiry_date"`
    licenseid   uint64 `gorm:"autoincrement;primarykey"`
}

type vehicle struct {
    vehicleclasskey   string `json:"vehicle_class_key"`
    vehicleclassvalue string `json:"vehicle_class_value"`
    vehicleid         uint64 `gorm:"autoincrement;primarykey"`
}

我是 gorm 新手,我想在数据库中保存 dlinformation 类型的对象,但由于存在 licensevehicle 类型的数组在 dlinformation 对象内,我无法将其保存在数据库中。

出现这样的错误:- 发现 struct dl-scraping/models 的无效字段。dlinformation 的字段许可证:为关系定义有效的外键或实现 valuer/scanner 接口

当我像这样定义外键时:-

Licenses []License `json:"licenses" gorm:"foreignKey:LicenseID;constraint:OnDelete:CASCADE"`

Vehicles []Vehicle `json:"vehicles" gorm:"foreignKey:VehicleID;constraint:OnDelete:CASCADE"`

然后出现错误:- vehicleid 和 licenseid 没有默认值


正确答案


您必须为每个自定义结构实现 ScanValue 方法,以便 gorm 知道如何存储它并从数据库中检索它。

好了,本文到此结束,带大家了解了《如何在golang中使用GORM框架将结构数组嵌入到另一个结构中并将其保存在数据库中》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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