GORM MySQL Implementation
This skill helps implement standard GORM models and database configurations, ensuring consistency across the project (e.g., proper time fields, table naming).
Execution Steps
Step 1: Define Entity Model
Create a new Go file in the common-service/entity (or module model) directory using the standard model template.
Template Usage:
- •Source:
templates/model.go.tmpl - •Target:
common-service/entity/{{FILENAME}}.go - •Variables:
- •
{{PACKAGE_NAME}}: Package name (usuallyentityormodel) - •
{{MODEL_NAME}}: Struct name (e.g.,User) - •
{{TABLE_NAME}}: Database table name (e.g.,users)
- •
Why use template?
The template includes CommonTime (CreateTime, UpdateTime, CreateBy, UpdateBy) which are mandatory for audit compliance in this project.
Step 2: Configure Database
Ensure etc/{{SERVICE}}.yaml has the database configuration.
Refer to references/config-examples.md (from go-zero-backend-init skill) or see below pattern:
yaml
InternalMysqlReader: Url: root:pass@tcp(127.0.0.1:3306)/db?charset=utf8mb4&parseTime=True&loc=Local MaxIdle: 10 MaxOpen: 100 InternalMysqlWriter: Url: root:pass@tcp(127.0.0.1:3306)/db?charset=utf8mb4&parseTime=True&loc=Local MaxIdle: 10 MaxOpen: 100
Step 3: Initialize in ServiceContext
In internal/svc/service_context.go, initialize the GORM DB connections.
go
// Example initialization reader, err := cfg.InitMysql(c.InternalMysqlReader) writer, err := cfg.InitMysql(c.InternalMysqlWriter) // Assign to context...
Templates Location
- •
templates/model.go.tmpl: Standard GORM model struct with CommonTime.
Reference
- •
references/: Detailed patterns for read-write separation logic.