Database & Models
Learn how to define data models and perform database operations using GORM.
Base Model
All models must embed the Base struct:
import "github.com/sven-victor/ez-console/pkg/model"
type Product struct {
model.Base
Name string `gorm:"size:128;not null" json:"name"`
Description string `gorm:"type:text" json:"description"`
Price float64 `gorm:"type:decimal(10,2)" json:"price"`
Stock int `gorm:"default:0" json:"stock"`
}
The Base struct provides:
ID- Internal auto-incrementing primary keyResourceID- Public UUID identifierCreatedAt- Creation timestampUpdatedAt- Last update timestampDeletedAt- Soft delete timestamp
Model Definition
Basic Model
type Category struct {
model.Base
Name string `gorm:"size:64;uniqueIndex" json:"name"`
}
Model with Relationships
type Product struct {
model.Base
Name string `gorm:"size:128" json:"name"`
Price float64 `gorm:"type:decimal(10,2)" json:"price"`
CategoryID uint `json:"-"`
Category *Category `gorm:"foreignKey:CategoryID" json:"category,omitempty"`
}
Many-to-Many Relationship
type User struct {
model.Base
Username string `json:"username"`
Roles []Role `gorm:"many2many:user_roles" json:"roles"`
}
type Role struct {
model.Base
Name string `json:"name"`
Users []User `gorm:"many2many:user_roles" json:"-"`
}
GORM Tags
Common tags:
gorm:"size:128"- Column sizegorm:"not null"- NOT NULL constraintgorm:"uniqueIndex"- Unique indexgorm:"default:0"- Default valuegorm:"type:text"- Column typegorm:"foreignKey:CategoryID"- Foreign keyjson:"name"- JSON field namejson:"-"- Exclude from JSON
Database Operations
Create
product := &Product{
Name: "Laptop",
Price: 999.99,
Stock: 10,
}
db.Create(product)
Read
// Find by ResourceID
var product Product
db.Where("resource_id = ?", resourceID).First(&product)
// Find all
var products []Product
db.Find(&products)
// With conditions
db.Where("price > ?", 100).Find(&products)
// With preload
db.Preload("Category").Find(&products)
Update
// Update single field
db.Model(&product).Update("stock", 20)
// Update multiple fields
db.Model(&product).Updates(map[string]interface{}{
"name": "New Name",
"price": 199.99,
})
// Save (updates all fields)
db.Save(&product)
Delete
// Soft delete
db.Delete(&product)
// Permanent delete
db.Unscoped().Delete(&product)
Migrations
Migrations are automatic in EZ-Console:
// Models are automatically migrated on server start
// Add your models in init() function
func init() {
// Register custom models for migration
db.AutoMigrate(&Product{}, &Category{})
}