GORM从已存在的表返回空字符串。

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

GORM returns empty string from already-existing table

问题

我在Postgres数据库(artwork_migrate_era)中有一张表。

我正在使用GORM。我发现为了使我的模型与已经存在的表一起工作,我需要使用TableName()方法,如下所示:

  1. type Era struct {
  2. id int `json:"id"`
  3. era_name string `json:"era_name"`
  4. last_modified time.Time `json:"last_modified"`
  5. }
  6. // 允许在数据库中使用gorm模型与已存在的表:https://stackoverflow.com/questions/66318666/golang-gorm-how-to-create-a-model-for-an-existing-table
  7. func (Era) TableName() string {
  8. return "artwork_migrate_era"
  9. }

我还在使用GIN进行请求处理:

  1. func main() {
  2. dsn := "...db_credentials..."
  3. db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
  4. if err != nil {
  5. panic("failed to connect to db")
  6. }
  7. db.AutoMigrate(&Era{})
  8. router := gin.Default()
  9. router.GET("/era/:id", func(c *gin.Context) {
  10. id := c.Param("id")
  11. var era Era
  12. db.Where("id = ?", id).Find(&era)
  13. c.JSON(http.StatusOK, gin.H{
  14. "Era": era.era_name,
  15. })
  16. })
  17. router.Run("localhost:8080")
  18. }

当我发出以下请求时:curl localhost:8080/era/4

我得到以下响应:{"Era":""}

我是否遗漏了一些明显的东西?

英文:

I have a table in a Postgres db (artwork_migrate_era)

I'm using GORM. I find that in order for my model to work with an already existing table, I need to use the TableName() method like so:

  1. type Era struct {
  2. id int `json:"id"`
  3. era_name string `json:"era_name"`
  4. last_modified time.Time `json:"last_modified"`
  5. }
  6. // allows to use gorm model with already-existing table in db: https://stackoverflow.com/questions/66318666/golang-gorm-how-to-create-a-model-for-an-existing-table
  7. func (Era) TableName() string {
  8. return "artwork_migrate_era"
  9. }

I'm also using GIN to make requests:

  1. func main() {
  2. dsn := "...db_credentials..."
  3. db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
  4. if err != nil {
  5. panic("failed to connect to db")
  6. }
  7. db.AutoMigrate(&Era{})
  8. router := gin.Default()
  9. router.GET("/era/:id", func(c *gin.Context) {
  10. id := c.Param("id")
  11. var era Era
  12. db.Where("id = ?", id).Find(&era)
  13. c.JSON(http.StatusOK, gin.H{
  14. "Era": era.era_name,
  15. })
  16. })
  17. router.Run("localhost:8080")
  18. }

when I make the following request: curl localhost:8080/era/4

I get get the following response: {"Era":""}

Am I just missing something obvious?

答案1

得分: 2

db.Where("id = ?", id).Find(&era) 无法将数据映射到您的结构体中,通过将结构体的首字母大写来导出所有成员。

英文:

db.Where("id = ?", id).Find(&era) would not be able to map the data to your struct export all the members of your struct by making the first letter Capital

huangapple
  • 本文由 发表于 2022年6月30日 19:52:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/72815313.html
匿名

发表评论

匿名网友

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

确定