加载中...

GORM 自动填充 UUID 的 2 种方式

使用 uuid 库手动生成

采用这个库:github.com/gofrs/uuid

在 GORM 中定义一个 BaseModel,并增加钩子函数:

Go
import "github.com/gofrs/uuid"

type BaseModel struct {
	ID            uuid.UUID
	CreatedAt     time.Time
	UpdatedAt     time.Time
	DeletedAt     gorm.DeletedAt `gorm:"index"`
	EffectiveTime *time.Time
}

func (m *BaseModel) BeforeCreate() (err error) {
	m.ID, err = uuid.NewV4()
	if err != nil {
		log.Logger.Err(err).Msg("uuid create failed")
		return fmt.Errorf("uuid create with ID failed, %w", err)
	}
	return nil
}

使用 postgresql 的 uuid-ossp 插件

首先要启用插件

要么手动 Navicat 界面上增加:

Untitled

要么执行查询语句:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

然后添加标签即可:

Go
import "github.com/gofrs/uuid"

type Model struct {
	ID            uuid.UUID `gorm:"type:uuid;primary_key;default:uuid_generate_v4()"`
	CreatedAt     time.Time
	UpdatedAt     time.Time
	DeletedAt     gorm.DeletedAt `gorm:"index"`
	EffectiveTime *time.Time
}

使用另一个插件:pgcrypto

如果你只需要随机生成(版本4)的UUID,那么请考虑使用来自 pgcrypto 模块的gen_random_uuid()函数。

这是官方文档说的,原因是 OSSP UUID库 已经没有很好维护了。

于是启用 pgcrypto 插件:

CREATE EXTENSION IF NOT EXISTS "pgcrypto";

然后添加标签:

Go
import "github.com/gofrs/uuid"

type Model struct {
	ID            uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
	CreatedAt     time.Time
	UpdatedAt     time.Time
	DeletedAt     gorm.DeletedAt `gorm:"index"`
	EffectiveTime *time.Time
}

更多 GORM 支持的字段标签

更多支持的标签字段请查看:https://gorm.io/zh_CN/docs/models.html#字段标签

参考文章

Example: golang gorm postgres uuid relation

How to Use UUID Key Type with Gorm

F.44. uuid-ossp

相关文章
2026-01-08 63分钟 12719 字

欢迎这位弟子 初入 A 股,你找了个证券公司的经理开户并调好合适的佣金,这就算入了我潇湘剑派了。 入门之后,带你的师兄甩给你一把剑,叫做同花顺,有了这把剑你就 …

阅读更多 →
2022-04-26 12分钟 2426 字

陈述 顾名思义,就是单调的栈,可严格可不严格。能够找到下一个更大/小的元素,同时能找到上一个大于等于/小于等于的元素。 通常是一维数组,要寻找任一个元素的右边 …

阅读更多 →
2022-12-25 19分钟 3875 字

🤔场景 既然回家了,有了家用路由器,就希望各个设备能够不需要安装对应的软件而直接科学上网、屏蔽广告等。 但原来的路由器太小众,没人提供相应的固件,也就是说没法 …

阅读更多 →