RapidGo
No results found

Models

Define database models with GORM, soft deletes, and query scopes.

RapidGo uses GORM as its ORM. Models are Go structs that map to database tables.

BaseModel

Embed models.BaseModel to get ID, timestamps, and soft delete support:

package models

import "github.com/RAiWorks/RapidGo/v2/database/models"

type Post struct {
    models.BaseModel
    Title   string `gorm:"size:255;not null" json:"title"`
    Body    string `gorm:"type:text" json:"body"`
    UserID  uint   `json:"user_id"`
}

BaseModel provides:

Field Type Description
ID uint Auto-incrementing primary key
CreatedAt time.Time Set automatically on create
UpdatedAt time.Time Updated automatically on save
DeletedAt gorm.DeletedAt Soft delete timestamp (indexed)

Query Scopes

Built-in scopes for soft-deleted records:

// Include soft-deleted records
db.Scopes(models.WithTrashed).Find(&posts)

// Only soft-deleted records
db.Scopes(models.OnlyTrashed).Find(&posts)

Model Registration

Register all models in a function for AutoMigrate:

// database/models/registry.go
func All() []interface{} {
    return []interface{}{
        &User{},
        &Post{},
        &Setting{},
    }
}

Wire it in cmd/main.go:

cli.SetModelRegistry(models.All)

CRUD Operations

// Create
post := models.Post{Title: "Hello", Body: "World", UserID: 1}
db.Create(&post)

// Read
var post models.Post
db.First(&post, id)

// Update
db.Model(&post).Updates(map[string]interface{}{"title": "Updated"})

// Soft delete
db.Delete(&post)

// Permanent delete
db.Unscoped().Delete(&post)

// List with pagination
var posts []models.Post
db.Offset(0).Limit(20).Find(&posts)

Scaffolding

go run cmd/main.go make:model Post
# Creates: database/models/post.go