Skip to content
Development
Skill

/gorm

GORM (Go ORM) development assistant. Use when the user needs to: (1) Create GORM models, (2) Define database schemas, (3) Perform CRUD operations, (4) Handle associations and relationships, (5) Write complex queries, (6) Implement migrations, (7) Use hooks and callbacks, (8)

From plugin
awesome-skills
306 skills

Claude Code

$ npx -y skills add fanqingxuan/awesome-skills --skill gorm --agent claude-code

SKILL.md

gorm.SKILL.md
name: gorm
description: "GORM (Go ORM) development assistant. Use when the user needs to: (1) Create GORM models, (2) Define database schemas, (3) Perform CRUD operations, (4) Handle associations and relationships, (5) Write complex queries, (6) Implement migrations, (7) Use hooks and callbacks, (8) Query data, (9) Insert data, (10) Update data, (11) Delete data, (12) Create tables, (13) Modify tables, or any other GORM development tasks. Triggers on phrases like \"创建 GORM 模型\", \"数据库查询\", \"GORM 关联\", \"GORM 开发\", \"查询数据\", \"写入数据\", \"更新数据\", \"删除数据\", \"创建表\", \"修改表\", \"操作数据库\", \"create GORM model\", \"database query\", \"GORM associations\", \"query data\", \"insert data\", \"update data\", \"delete data\", \"create table\", \"modify table\"."

GORM 开发指南

GORM 是 Go 语言最流行的 ORM 库,提供完整的数据库操作功能。

⚠️ 重要说明

**本 skill 专注于 GORM 的传统 API(Traditional API),不使用泛型方式。**

所有示例代码均使用传统的链式调用方式,确保与现有代码和 GORM 插件的完全兼容性。

传统 API vs 泛型 API

// ✅ 使用传统 API(推荐)
var user User
db.Where("name = ?", "John").First(&user)
db.Create(&user)
db.Model(&user).Update("age", 30)

// ❌ 不使用泛型 API
// result := gorm.Query[User](db).Where("name = ?", "John").First()

快速开始

安装

go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
go get -u gorm.io/driver/postgres
go get -u gorm.io/driver/sqlite

连接数据库

package main

import (
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

func main() {
    // MySQL
    dsn := "user:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    // PostgreSQL
    // dsn := "host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable"
    // db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

    // SQLite
    // db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
}

模型定义

基础模型

type User struct {
    ID        uint           `gorm:"primaryKey"`
    Name      string         `gorm:"size:100;not null"`
    Email     string         `gorm:"uniqueIndex;size:100"`
    Age       int            `gorm:"default:0"`
    Birthday  *time.Time
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt gorm.DeletedAt `gorm:"index"`
}

使用 gorm.Model

type User struct {
    gorm.Model
    Name  string
    Email string
}

// gorm.Model 包含:
// ID        uint
// CreatedAt time.Time
// UpdatedAt time.Time
// DeletedAt gorm.DeletedAt

字段标签

type User struct {
    ID        uint      `gorm:"primaryKey"`
    Name      string    `gorm:"size:100;not null;index"`
    Email     string    `gorm:"uniqueIndex;size:100"`
    Age       int       `gorm:"default:18"`
    Active    bool      `gorm:"default:true"`
    Salary    float64   `gorm:"type:decimal(10,2)"`
    Profile   string    `gorm:"type:text"`
    Extra     string    `gorm:"-"` // 忽略该字段
}

CRUD 操作

创建

// 创建单条记录
user := User{Name: "John", Email: "john@example.com", Age: 30}
result := db.Create(&user)
// user.ID 返回插入数据的主键
// result.Error 返回错误
// result.RowsAffected 返回插入记录的条数

// 批量创建
users := []User{
    {Name: "John", Email: "john@example.com"},
    {Name: "Jane", Email: "jane@example.com"},
}
db.Create(&users)

// 使用 Map 创建
db.Model(&User{}).Create(map[string]interface{}{
    "Name": "John",
    "Age":  30,
})

查询

// 获取第一条记录
var user User
db.First(&user)
// SELECT * FROM users ORDER BY id LIMIT 1;

// 获取最后一条记录
db.Last(&user)

// 根据主键查询
db.First(&user, 10)
// SELECT * FROM users WHERE id = 10;

// 查询所有记录
var users []User
db.Find(&users)

// 条件查询
db.Where("name = ?", "John").First(&user)
db.Where("name = ? AND age >= ?", "John", 20).Find(&users)
db.Where("name IN ?", []string{"John", "Jane"}).Find(&users)
db.Where("name LIKE ?", "%john%").Find(&users)

// Struct 条件
db.Where(&User{Name: "John", Age: 20}).First(&user)

// Map 条件
db.Where(map[string]interface{}{"name": "John", "age": 20}).Find(&users)

// Not 条件
db.Not("name = ?", "John").Find(&users)

// Or 条件
db.Where("name = ?", "John").Or("name = ?", "Jane").Find(&users)

// 选择特定字段
db.Select("name", "age").Find(&users)

// 排序
db.Order("age desc, name").Find(&users)

// 限制和偏移
db.Limit(10).Offset(5).Find(&users)

// 分组和聚合
db.Model(&User{}).Select("name, sum(age) as total").Group("name").Having("total > ?", 100).Find(&results)

更新

// 更新单个字段
db.Model(&user).Update("name", "John Doe")

// 更新多个字段
db.Model(&user).Updates(User{Name: "John", Age: 30})
db.Model(&user).Updates(map[string]interface{}{"name": "John", "age": 30})

// 更新选定字段
db.Model(&user).Select("name").Updates(map[string]interface{}{"name": "John", "age": 30})
// 只更新 name

// 批量更新
db.Model(&User{}).Where("active = ?", true).Update("name", "hello")

// 使用表达式更新
db.Model(&User{}).Update("age", gorm.Expr("age + ?", 1))

删除

// 删除记录
db.Delete(&user)
// DELETE FROM users WHERE id = 10;

// 根据主键删除
db.Delete(&User{}, 10)
db.Delete(&User{}, []int{1, 2, 3})

// 批量删除
db.Where("name = ?", "John").Delete(&User{})

// 软删除(需要 DeletedAt 字段)
db.Delete(&user)
// UPDATE users SET deleted_at = '当前时间' WHERE id = 10;

// 永久删除
db.Unscoped().Delete(&user)

// 查询包含软删除的记录
db.Unscoped().Where("age = ?", 20).Find(&users)

关联关系

Belongs To

type User struct {
    gorm.Model
    Name      string
    CompanyID int
    Company   Company
}

type Company struct {
    gorm.Model
    Name string
}

// 查询时预加载
db.Preload("Company").Find(&users)

Has One

type User struct {
    gorm.Model
    Name    string
    Profile Profile
}

type Profile struct {
    gorm.Model
    UserID uint
    Bio    string
}

// 预加载
db.Preload("Profile").Find(&users)

Has Many

type User struct {
    gorm.Model
    Name   string
    Orders []Order
}

type Order struct {
    gorm.Model
    UserID uint
    Amount float64
}

// 预加载
db.Preload("Orders").Find(&users)

Many To Many

type User struct {
    gorm.Model
    Name  string
Read more
@fanqingxuan
Ships withawesome-skills

Agent Skills for modern software development frameworks with best practices and coding standards.

Stars on GitHub

Momentum

stars in total
30
Star history of fanqingxuan/awesome-skills on GitHub, a chart by star-history.com

Other skills on awesome-skills.

eino

eino

Eino LLM/AI application development framework assistant (Golang). Use when the user needs to: (1) Build AI agents, (2) Create LLM…

hyperf

hyperf

Hyperf 3.1 framework development assistant. Use when the user needs to: (1) Create Hyperf controllers, (2) Create Hyperf models,…

laravel12

laravel12

Laravel 12 framework development assistant. Use when the user needs to: (1) Create Laravel controllers, (2) Create Laravel…

webman

webman

Webman framework development assistant. Use when the user needs to: (1) Create Webman controllers, (2) Create Webman models, (3)…

More skills from other plugins.

brainstorming
Auto-invoked

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or…

@obra@obraInstall Skill
ask-matt

ask-matt

Ask which skill or flow fits your situation. A router over the skills in this repo.

skills2w309k
@mattpocock@mattpocockInstall Skill
accessibility
Auto-invoked

accessibility

Design, implement, and audit accessible UI to WCAG 2.2 Level AA across Web, iOS, and Android — semantic ARIA roles and labels,…

ecc2w293k
@affaan-m@affaan-mInstall Skill
compiler-commit

compiler-commit

Use when you want to verify compiler changes and commit with the correct convention. Runs tests, lint, and format, then commits…

react5d252k
@facebook@facebookInstall Skill

Questions about gorm.

Which coding agents can use gorm?
gorm installs in Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf with the skills CLI, using each agent's flag shown on this page. Flowy's auto-invocation, which fires a skill when your prompt matches, runs in Claude Code only.