
在 Gorm 中,实现与值数组的关系是一项非常有用的功能。Gorm 是一个流行的 Go 语言 ORM(对象关系映射)库,它允许开发者使用 Go 语言来操作数据库。与传统的关系型数据库不同,值数组是一种特殊的数据结构,它允许将多个值作为一个整体存储在数据库中的某个字段中。这对于存储一些复杂的数据结构或者提高查询效率都非常有帮助。在本文中,我将向大家介绍如何在 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 }









