任务三

This commit is contained in:
Yvan 2026-01-07 11:03:52 +08:00
parent 07b902d87c
commit cd473c0e17
1 changed files with 51 additions and 0 deletions

51
cmd/gen/main.go Normal file
View File

@ -0,0 +1,51 @@
package main
import (
"fmt"
"path/filepath"
"runtime"
"gorm.io/driver/mysql"
"gorm.io/gen"
"gorm.io/gorm"
)
func main() {
// 连接数据库
dsn := "root:Xu950329.@tcp(localhost:3306)/spa?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic(fmt.Errorf("connect db fail: %w", err))
}
// 获取项目根目录
_, filename, _, _ := runtime.Caller(0)
projectRoot := filepath.Dir(filepath.Dir(filepath.Dir(filename)))
// 创建gen实例
g := gen.NewGenerator(gen.Config{
OutPath: filepath.Join(projectRoot, "internal/data/query"),
ModelPkgPath: filepath.Join(projectRoot, "internal/data/model"),
Mode: gen.WithDefaultQuery | gen.WithQueryInterface,
FieldNullable: true,
FieldCoverable: false,
FieldSignable: false,
FieldWithIndexTag: true,
FieldWithTypeTag: true,
})
g.UseDB(db)
// 字段名映射,避免与方法名冲突
fieldOpts := []gen.ModelOpt{
gen.FieldRename("table_name", "TblName"),
gen.FieldRename("table", "TblName"), // 避免与Table()方法冲突
}
// 生成所有表的model和query
allTables := g.GenerateAllTable(fieldOpts...)
g.ApplyBasic(allTables...)
// 执行生成
g.Execute()
}