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

标签 :
相关文章
KMP 算法:找子串的位置

简介 字符串的算法中,有一个是做模式匹配,让你找子串的位置。 如果用暴力解法,那就是一个双重 for 循环,以主串的每个字符为开头,往后走,看是不是跟子串完全一致。这样的算法时间复杂度是 $O(n \times m)$。有没有更好的算法呢?

阅读更多
如何在没有U盘的情况下,重新安装操作系统?无U盘也能装Ubuntu!

动机 windows11 是在是跑不起来了,卡的要死 咱还是装个 Ubuntu 好让我跑 microk8s ! easyUEFI 没有U盘安装ubuntu18(linux),EasyUEFI安装ubuntu_大蜻科的博客-CSDN博客_无u盘安装ubuntu18 使用easyuefi

阅读更多
BlockSuite 一款 Block Style 的编辑器,仅仅是编辑器!

先说结论 我的博客不太适合用 BlockSuite 作为编辑器,因为: 不知道如何渲染,我可以编辑,但是如何展示给匿名用户看? SEO 不太明确,也想着转成 HTML 来做,但是成本太高? 其他博主的调研:https://blog.nineya.com/archives/154.html 开始! 学习一下:https://block-suite.com/ Scratch(QuickStart) 简单安装一下,目前是 canary 版本, AFFiNE 也是用的这个版本,每次都打包的 master 分支,基本上每天都有更新。

阅读更多