Cod*_*der 2 mysql model go go-gorm
我在当前的应用程序中使用Gorm ORM。我有一个模型通讯员到许多具有相同表结构(即列名和类型)的表。所以我的要求是如何在执行查询时动态更改表名。
例如
我有像 Product.go 这样的产品模型
type Product struct{
ID int
Name strig
Quantity int
}
Run Code Online (Sandbox Code Playgroud)
我们有不同的产品,如衬衫、牛仔裤等,我们有相同的桌子,如衬衫、牛仔裤。
现在我想根据产品的名称查询产品,我们该怎么做,也希望通过迁移创建表。但是只有一种模型比我们如何使用自动迁移功能与 Gorm 一起运行。
您几乎可以通过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)
Run Code Online (Sandbox Code Playgroud)
不幸的是,db.Find()当您需要查询多条记录时,这不起作用......解决方法是在执行查询之前指定您的表
prods := []*Product{}
db.Table("jeans").Where("quantity > 0").Find(&prods)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2385 次 |
| 最近记录: |