每日一悟:为什么go 数据表的orm,很多地方用指针呢
例子
package models
import (
"time"
"github.com/jinzhu/gorm"
)
type YyMedicineSaleOrder struct {
ID uint `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"id"` // 匹配自增ID
HospitalID *int `gorm:"column:hospital_id" json:"hospital_id"` // 医院id
OrderNo *string `gorm:"size:100;column:order_no" json:"order_no"` // 进货单号
Path *string `gorm:"size:255;column:path" json:"path"` // 文件路径
Bz *string `gorm:"size:100;column:bz" json:"bz"` // 备注
IsMedicineMatchUpdate int `gorm:"NOT NULL;DEFAULT:2;column:is_medicine_match_update" json:"is_medicine_match_update"` // 是否有药物匹配更新,1是,2否
Status int `gorm:"NOT NULL;DEFAULT:1;column:status" json:"status"` // 1,未匹配完成。2,匹配完成(无需匹配)3,生成应收中,4,生成应收成功,5,生成应收失败。6,匹配过(未匹配完)
Error *string `gorm:"size:255;column:error" json:"error"` // job执行错误信息
CreatedAt *time.Time `gorm:"column:created_at" json:"created_at"`
Createtime uint64 `gorm:"column:createtime" json:"createtime"` // 创建时间
JobStatus *int `gorm:"DEFAULT:2;column:job_status" json:"job_status"` // job是否正在执行,1,是,2否。
DateMonth *time.Time `gorm:"type:date;column:date_month" json:"date_month"` // 单据生成的年月
Type int8 `gorm:"NOT NULL;column:type" json:"type"` // 类型:1外采,2内部
}
// TableName sets the insert table name for this struct type
func (y *YyMedicineSaleOrder) TableName() string {
return "yy_medicine_sale_order"
}
解析:GORM 鼓励使用指针类型
在Go语言的 GORM 中,指针用来表示数据库中的NULL值。如果我们在结构体中定义字段类型为非指针的基本类型,例如 int
或者 string
,那么在Go语言中这些类型是无法表示NULL的。如果数据库字段有可能出现NULL情况,GORM查询出来对于Go语言来说都会是类型的零值,例如 int 类型字段的零值是0,string类型字段的零值是””。
但是在一些场景中,数据库字段的 NULL 和 零值 在业务含义上可能是两种完全不同的状态,所以为了解决这个问题,GORM 鼓励使用指针类型。当数据库字段为NULL时,对应的将是nil;当数据库字段有具体值时,将对应具体的值。
当然,如果你确定这个字段一定不会是NULL值,你也可以直接使用非指针类型。例如我看到你的部分字段有 NOT NULL 约束,那么这些字段在 Go 语言的结构体定义上可以不用指针。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: