How to dynamically set table name for every query in go-pg?

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

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()

huangapple
  • 本文由 发表于 2016年10月25日 06:50:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/40228803.html
匿名

发表评论

匿名网友

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

确定