acmestack / gorm-plus

Gorm-plus是基于Gorm的增强版,类似Mybatis-plus语法。Gorm-plus is based on an enhanced version of Gorm, similar to Mybatis-plus syntax.
https://github.com/acmestack/gorm-plus/wiki
Apache License 2.0
276 stars 41 forks source link

support multiple gorm #79

Open philhuan opened 7 months ago

philhuan commented 7 months ago

We need to connect to multiple databases in our project, but gplus's gorm as a global variable. can gplus support multi gorm??

afumu commented 7 months ago

Good idea, we can add it later, or if you're interested, you can submit pr

MrYZhou commented 6 months ago

我们需要连接到项目中的多个数据库,但 gplus 的 gorm 是一个全局变量。 gplus 可以支持 multi gorm 吗?

这个似乎和plus没有太大的关系我写了个方法在有需要的地方自己去切换数据源。类似这样: var gormDb gorm.DB var gormDbMap = make(map[string]gorm.DB)

func DbChange(tag string){ // gplus的连接的数据库 gormDb := gormDbMap[tag] gplus.Init(gormDb) } func DbInit(tag string,url string) { var err error gormDb, err = gorm.Open(mysql.Open(url+"?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{ Logger: logger.Default.LogMode(logger.Info), NamingStrategy: schema.NamingStrategy{ TablePrefix: "", // 数据库表前缀 SingularTable: true, // 不用给表名加复数 NoLowerCase: false, // 要不要把表名全小写 }, // Logger: logger.Discard, // 不输出日志 }) if err != nil { log.Println(err) } gormDbMap[tag] = gormDb }

philhuan commented 6 months ago

In actual projects, multiple data sources must be used concurrently at the same time, so the value of global variables cannot be switched through one method.

We can provide API of gplus through the methods of an object, and then distinguish different data sources through the attribute values ​​​​of the object.

For example:


gorm1Db, _ = gorm.Open()
gorm2Db, _ = gorm.Open()

gplus1Db = gplus.New(gorm1Db)
gplus2Db = gplus.New(gorm2Db)

users1, resultDb := gplus1Db.SelectList[User](nil)
users2, resultDb := gplus2Db.SelectList[User](nil)

However, this will change the API of gplus.