GORM – 在运行时更改数据库的 Golang 库

huangapple go评论79阅读模式
英文:

GORM - Golang Change Database at Runtime

问题

在用户界面中,您可以通过下拉菜单选择不同的选项,这些选项与不同数据库中保存的数据相关。我已经为这些数据创建了模型,并且由于数据库之间的表结构相同,我希望根据用户选择的选项简单地在数据库之间切换。

在 GORM 2.0 中如何实现这一点?我希望避免在查询中指定 "database.tableName",因为我经常使用以下模式:

db.Model(&model).Where...

我已经找到了一种方法,但我想知道是否有一种更优雅的方式来处理 gorm.DB 对象中的这个问题(或者是否有更优雅的方式)。

目前的解决方案是:

在存储库中,在执行任何数据库操作之前使用以下代码:

r.db.Exec("use " + utils.GetDB())

并使用 API 中间件来捕捉下拉菜单的任何更改,并设置一个与所需数据库相关的全局变量。

非常感谢!

英文:

In the UI you can select different options in a dropdown, which relate to data held in different databases. I have created models for the data, and as the table schemas are the same between the DBs, I would like to simply switch between the DBs according to which option the user has selected.

How can this be achieved in GORM 2.0? I would prefer to avoid specifying the "database.tableName" in the queries, as I have frequently used the

db.Model(&model).Where...

pattern.

I have figured out a method, but I was interested to see if there was a way of handling this in the gorm.DB object (or more elegantly at all!).

Current solution:

In the repository, before executing any database operation use the following:

r.db.Exec("use " + utils.GetDB())

and use the API middleware to pick up any changes to the dropdown and set a global variable pertaining to the required database.

Many thanks in advance.

答案1

得分: 0

在没有其他答案的情况下,这是我决定使用的解决方案的指南

var db map[string]*gorm.DB

db = make(map[string]*gorm.DB)
db["db1"], err = gorm.Open(mysql.Open(config.DbURL()), &gorm.Config{})
db["db2"], err = gorm.Open(mysql.Open(config.DbURL()), &gorm.Config{})
db["db3"], err = gorm.Open(mysql.Open(config.DbURL()), &gorm.Config{})

然后,当需要时,可以编写一个函数来返回所需的数据库名称,返回您希望使用的实例。

db[dbname].Table("table1").Select....
英文:

In the absence of other answers, here is a guide to the solution I decided to use:

var db map[string]*gorm.DB

db = make(map[string]*gorm.DB)
db["db1"], err = gorm.Open(mysql.Open(config.DbURL()), &gorm.Config{})
db["db2"], err = gorm.Open(mysql.Open(config.DbURL()), &gorm.Config{})
db["db3"], err = gorm.Open(mysql.Open(config.DbURL()), &gorm.Config{})

and then when required have a function to return the required database name, returning the instance you wish to use.

db[dbname].Table("table1").Select....

huangapple
  • 本文由 发表于 2022年2月14日 22:41:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/71113656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定