go-platform/models/init.go
2026-04-01 18:15:43 +08:00

55 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package models
import (
"fmt"
"github.com/beego/beego/v2/client/orm"
beego "github.com/beego/beego/v2/server/web"
_ "github.com/go-sql-driver/mysql"
)
// Orm 全局 ORM 对象,供业务层和控制器使用
var Orm orm.Ormer
// Init 初始化模型层资源(数据库连接、模型注册等)。
func Init(_ string) {
// 从配置读取数据库连接信息
user, _ := beego.AppConfig.String("mysqluser")
pass, _ := beego.AppConfig.String("mysqlpass")
urls, _ := beego.AppConfig.String("mysqlurls")
dbname, _ := beego.AppConfig.String("mysqldb")
if user == "" || urls == "" || dbname == "" {
panic("数据库配置(mysqluser/mysqlurls/mysqldb) 未正确设置")
}
// 组装 DSNuser:pass@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, pass, urls, dbname)
// 注册默认数据库
if err := orm.RegisterDataBase("default", "mysql", dsn); err != nil {
panic("注册数据库失败: " + err.Error())
}
// 注册模型
orm.RegisterModel(
new(Tenant),
new(TenantUser),
new(SystemMenu),
new(AdminUser),
new(AdminRole),
new(SystemFile),
new(SystemFilesCategory),
new(SystemEmail),
new(SystemSMS),
new(SystemSMSTask),
new(SystemOperationLog),
new(SystemDomainPool),
new(SystemTenantDomain),
new(SystemModules),
)
// 创建全局 Ormer
Orm = orm.NewOrm()
}