GORM 聲明模型

2022-03-04 16:49 更新

模型定義

模型是標(biāo)準(zhǔn)的 struct,由 Go 的基本數(shù)據(jù)類型、實現(xiàn)了 Scanner 和 Valuer 接口的自定義類型及其指針或別名組成

例如:

type User struct {
	ID           uint
	Name         string
	Email        *string
	Age          uint8
	Birthday     *time.Time
	MemberNumber sql.NullString
	ActivatedAt  sql.NullTime
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

約定

GORM 傾向于約定,而不是配置。默認(rèn)情況下,GORM 使用 ID 作為主鍵,使用結(jié)構(gòu)體名的蛇形復(fù)數(shù)作為表名,字段名的蛇形作為列名,并使用 CreatedAt、UpdatedAt 字段追蹤創(chuàng)建、更新時間
遵循 GORM 已有的約定,可以減少您的配置和代碼量。如果約定不符合您的需求,GORM 允許您自定義配置它們

gorm.Model

GORM 定義一個 gorm.Model 結(jié)構(gòu)體,其包括字段 ID、CreatedAt、UpdatedAt、DeletedAt

// gorm.Model 的定義
type Model struct {
	ID        uint `gorm:"primaryKey"`
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt gorm.DeletedAt `gorm:"index"`
}

你可以將它嵌入到你的結(jié)構(gòu)體中,以包含這幾個字段

嵌入結(jié)構(gòu)體

對于匿名字段,GORM 會將其字段包含在父結(jié)構(gòu)體中,例如:

type User struct {
	gorm.Model
	Name string
}

// 等效于
type User struct {
	ID        uint `gorm:"primaryKey"`
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt gorm.DeletedAt `gorm:"index"`
	Name      string
}

對于正常的結(jié)構(gòu)體字段,你也可以通過標(biāo)簽 embedded 將其嵌入,例如:

type Author struct {
	Name  string
	Email string
}

type Blog struct {
	ID      int
	Author  Author `gorm:"embedded"`
	Upvotes int32
}

// 等效于
type Blog struct {
	ID      int64
	Name    string
	Email   string
	Upvotes int32
}

并且,您可以使用標(biāo)簽 embeddedPrefix 來為 db 中的字段名添加前綴,例如:

type Blog struct {
	ID      int
	Author  Author `gorm:"embedded;embeddedPrefix:author_"`
	Upvotes int32
}

// 等效于
type Blog struct {
	ID          int64
	AuthorName  string
	AuthorEmail string
	Upvotes     int32
}


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號