mysql - 如何在gorm模型中传递动态表名
问题描述
我正在为我当前的应用程序使用Gorm ORM。我有一个模型对应于许多具有相同表结构(即列名和类型)的表。所以我的要求是如何在查询时动态更改表名。
例如
我有像 Product.go 这样的产品模型
type Product struct{
ID int
Name strig
Quantity int
}
我们有不同的产品,如衬衫、牛仔裤等,我们有相同的桌子,如衬衫、牛仔裤。
现在我想根据产品名称查询产品,我们怎么能做到这一点,也希望通过迁移创建表。但是只有一个模型比我们如何运行使用 Gorm 的 Automigrate 功能。
解决方案
通过使用结构内的字段,您几乎就在那里table
:
type Product struct{
ID int
Name strig
Quantity int
// private field, ignored from gorm
table string `gorm:"-"`
}
func (p Product) TableName() string {
// double check here, make sure the table does exist!!
if p.table != "" {
return p.table
}
return "products" // default table name
}
// for the AutoMigrate
db.AutoMigrate(&Product{table: "jeans"}, &Product{table: "skirts"}, &Product{})
// to do the query
prod := Product{table: "jeans"}
db.Where("quantity > 0").First(&prod)
db.Find()
不幸的是,当您需要查询多条记录时,这不起作用...解决方法是在执行查询之前指定您的表
prods := []*Product{}
db.Table("jeans").Where("quantity > 0").Find(&prods)
推荐阅读
- postgresql - 如何在数据库中设置另一个用户名?
- excel - 基本 Excel 测验 [需要帮助]
- javascript - 谷歌地图如何拦截带有触摸板的笔记本电脑上的滑动/捏合手势?
- sql-server - 顺序编号列更新
- r - 如何选择列中具有相等值的行
- excel - 排序参考无效?
- ios - RxSwift Disposable 属性 isDisposed 始终为 false 或 Disposable 闭包更新调用以取消工作任务
- r - 基于 R 中的变量从 data.frames 列表中设置子集
- html - 警告:必须有一个有效的 `as` 值
- ios - @supports 指令在 Safari iOS 中的工作原理