GORM 自动填充 UUID 的 2 种方式

目录

使用 uuid 库手动生成

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

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

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";

然后添加标签即可:

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";

然后添加标签:

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

标签 :
comments powered by Disqus

相关文章

beancount-gs 一款 self-hosted 复式记账程序,简化你的记账方式!

本程序将部署在 macOS 上,不使用 Docker(mac 上的 Docker 太卡了) 动机 我利用 beancount 来记账已经有一段时间了,但有些痛点问题困扰着我: 没有 web 界面,fava 真的只能用来展示和分析且不好理解,需要有一个方便记账的界面 text

阅读更多

如何在 React 中轻松路由?使用 React Router!

开始 import React from "react"; import ReactDOM from "react-dom/client"; import { createBrowserRouter, RouterProvider, } from "react-router-dom"; import Root from "./routes/root"; const router = createBrowserRouter([ { path: "/", element: <Root />, }, ]); ReactDOM.createRoot(document.getElementById("root")).render( <React.StrictMode> <RouterProvider router={router} /> </React.StrictMode> ); root 路由比较特殊。 Not Found import ErrorPage from "./error-page"; const router = createBrowserRouter([ { path: "/", element: <Root />, **errorElement: <ErrorPage />,** }, ]); ReactDOM.createRoot(document.getElementById("root")).render( <React.StrictMode> <RouterProvider router={router} /> </React.StrictMode> ); 嵌套路由 让 <Contact /> 渲染在 <Root /> 的 children(<Outlet />) 中: const router = createBrowserRouter([ { path: "/",

阅读更多

单调栈

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

阅读更多