使用 Gorm 将值数组关联到模型中的数据
时间:2024-02-15
浏览:322
作者:佚名
最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《使用 Gorm 将值数组关联到模型中的数据》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~
问题内容
我正在尝试使用 go 和 gorm 实现发票应用程序的模型。我已经定义了发票结构,并希望包含来自单独结构的发票行项目。
type invoice struct {
base
companyid string `gorm:"not null"`
company company
invoiceno string `gorm:"not null"`
currency string `gorm:"not null;default:'gbp'"`
total float64 `gorm:"not null"`
terms int `gorm:"not null;default:30"`
issueddate time.time `gorm:"not null"`
duedate time.time `gorm:"not null"`
paid bool `gorm:"not null"`
lineitems []lineitem `gorm:"foreignkey:invoiceid"`
void bool `gorm:"default:false"`
}
这是我的 lineitem 结构。
type lineitem struct {
base
service string `gorm:"not null"`
description string `gorm:"not null;"`
amount float64
count int
unitbase string `gorm:"not null;default:'days'"` // days or hours
total float64 `gorm:"not null"`
}
当我尝试构建应用程序时,出现以下错误。
... got error invalid field found for struct github.com/repo/API/database/models.Invoice's field LineItems: define a valid foreign key for relations or implement the Valuer/Scanner interface
我的想法是,我可以定义一个有限的设置订单项,可以从固定费率和说明中进行选择,以限制重复。
我不确定我的处理方式是否正确。
所以我的问题是,是否可以通过这种方式包含关系模型中的项目数组?
正确答案
根据您的列名称,我可以想到三种方法来实现此目的:
使用默认语法(无
gorm:foreignkey)type invoice struct { id //this is the primary key, may also be in your base model lineitems []lineitem ..other fields } type lineitem struct { id //primary key of lineitem invoiceid //automatically this will be your foreign key ..other fields }指定自定义外键(假设第二个结构具有不同的列名称,您希望将其作为外键)
type invoice struct { id //this is the primary key, may also be in your base model lineitems []lineitem `gorm:"foreignkey:parentid"` ..other fields } type lineitem struct { id //primary key of lineitem parentid //this is the custom column referencing invoice.id ..other fields }或者两个结构体具有不同的列名称
type Invoice struct { ID //this is the primary key, may also be in your base model InvoiceNum Lineitems []LineItem `gorm:"foreignKey:ParentNum;references:InvoiceNum"` ..other fields } type LineItem struct { ID //primary key of LineItem ParentNum //this is now referencing Invoice.InvoiceNum ..other fields }
今天关于《使用 Gorm 将值数组关联到模型中的数据》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.26
11.26
11.26
11.26
11.26
11.26
热门专题
