英文:
How to dynamically set table name for every query in go-pg?
问题
我有一堆类似的临时表,我想使用go-pg的ORM来查询它们。我找不到在选择期间动态更改查询表的方法:
import "gopkg.in/pg.v4"
type MyModel struct {
TableName struct{} `sql:"temp_table1"`
Id int64
Name string
}
var mymodels []MyModel
err := db.Model(&mymodels).Column("mymodel.id", "mymodel.name").Select()
这将根据模型的TableName
定义查询temp_table1
。有没有办法将表名作为参数传递,以便我可以查询temp_table_X
?
(我可以不使用ORM,而是使用原始的db.Query()
,但我想看看是否有一种使用ORM的方法)。
英文:
I have a bunch of similar temp tables which I am trying to query using go-pg's ORM. I can't find a way to dynamically change the queried table during a select:
import "gopkg.in/pg.v4"
type MyModel struct {
TableName struct{} `sql:"temp_table1"`
Id int64
Name string
}
var mymodels []MyModel
err := db.Model(&mymodels).Column("mymodel.id", "mymodel.name").Select()
This will query temp_table1
as defined in the model's TableName
. Is there a way to pass table name as a parameter so I can query temp_table_X
?
(I can just not use ORM and go with raw db.Query()
, but I wanted to see if there is a way to use ORM).
答案1
得分: 2
在github上得到了一个答案:
err := db.Model().TableExpr("temp_table_999 AS mymodel").Column("mymodel.id", "mymodel.name").Select(&mymodels)
英文:
Got an answer on github:
err := db.Model().TableExpr("temp_table_999 AS mymodel").Column("mymodel.id", "mymodel.name").Select(&mymodels)
答案2
得分: 0
似乎你可以直接指定表格,代码如下:db.Model(&mymodels).Table('temp_table1').Column("mymodel.id", "mymodel.name").Select()
。
英文:
Seems you can specify the table directly: db.Model(&mymodels).Table('temp_table1').Column("mymodel.id", "mymodel.name").Select()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论