首页 > 解决方案 > 如何在gorm模型中传递动态表名

问题描述

我正在为我当前的应用程序使用Gorm ORM。我有一个模型对应于许多具有相同表结构(即列名和类型)的表。所以我的要求是如何在查询时动态更改表名。

例如

我有像 Product.go 这样的产品模型

type Product struct{
  ID int
  Name strig
  Quantity int
}

我们有不同的产品,如衬衫、牛仔裤等,我们有相同的桌子,如衬衫、牛仔裤。

现在我想根据产品名称查询产品,我们怎么能做到这一点,也希望通过迁移创建表。但是只有一个模型比我们如何运行使用 Gorm 的 Automigrate 功能。

标签: mysqlgomodelgo-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)

db.Find()不幸的是,当您需要查询多条记录时,这不起作用...解决方法是在执行查询之前指定您的表

prods := []*Product{}
db.Table("jeans").Where("quantity > 0").Find(&prods)

推荐阅读