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

标签 :
相关文章
如何在 React 中进行状态管理?使用 Zustand!

计数器 tsx 复制 已复制! import { create } from 'zustand' const useStore = create(set => ({ count: 1, inc: () => set(state => ({ count: state.count + 1 })), })) function Controls() { const inc = useStore(state => state.inc) return <button onClick={inc}>one up</button> } function Counter() { const count = useStore(state => state.count) return <h1>{count}</h1> } 用法 创建状态 state 操作 action Basic typescript usage doesn’t require anything special except for writing create<State>()(...) instead of create(...)…

阅读更多
Snapcast 多房间音频控制一体化

动机 想要手头的两台 MBP 能同时无延迟播放音频,拒绝使用直播流的形式。 Tip update at 2025-04-13

阅读更多
MacBook 上安装 ArchLinux 双系统

动机 希望将闲置的 2018 款 MBP 利用起来,整成一台 Linux 服务器就好了,因为 macOS 上的 Docker 非常难用,再加上我比较爱折腾,于是有了这个想法。 主要参考这个 wiki:https://wiki.t2linux.org Tip

阅读更多