簡體   English   中英

如何在gorm model中傳遞動態表名

[英]How to pass dynamic table name in gorm model

我正在為我當前的應用程序使用Gorm ORM。 我有一個 model 對應於許多具有相同表結構(即列名和類型)的表。 所以我的要求是如何在查詢時動態更改表名。

例如

我有產品 model 像 Product.go

type Product struct{
  ID int
  Name strig
  Quantity int
}

我們有不同的產品,如襯衫、牛仔褲等,我們有相同的桌子,如襯衫、牛仔褲。

現在我想根據產品名稱查詢產品,我們怎么能做到這一點,也希望通過遷移創建表。 但是只有一個 model 比我們如何運行與 Gorm 一起使用 Automigrate 功能。

為 GORM v2 更新

已棄用: TableName將不再允許動態表名,其結果將被緩存以備將來使用。

有一種更簡單的方法可以使用相同的結構創建多個表:

// Create table `shirts` & `jeans` with the same fields as in struct Product
db.Table("shirts").AutoMigrate(&Product{})
db.Table("jeans").AutoMigrate(&Product{})

// Query data from those tables
var shirts []Product
var jeans []Product
db.Table("shirts").Find(&shirts)
db.Table("jeans").Where("quantity > 0").Find(&shirts)

但是,現在再考慮一下,我建議使用嵌入式結構,這樣您就不必在每個查詢中調用Table並且您還可以在每個 model 中擁有額外的字段,同時仍然共享相同的表結構。

type ProductBase struct {
  ID int
  Name strig
  Quantity int
}

type Shirt struct {
  ProductBase
  NeckType string
}

type Jean struct {
  ProductBase
  Ripped bool
}

db.AutoMigrate(&Shirt{}, &Jean{})

shirt, jeans := Shirt{}, make([]Jean, 0)
db.Where("neck_type = ?", "Mandarin Collar").Last(&shirt)
db.Where("ripped").Find(&jeans)

GORM v1 的舊答案

通過使用結構內的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM