英文:
GORM returns empty string from already-existing table
问题
我在Postgres数据库(artwork_migrate_era)中有一张表。
我正在使用GORM。我发现为了使我的模型与已经存在的表一起工作,我需要使用TableName()方法,如下所示:
type Era struct {
id int `json:"id"`
era_name string `json:"era_name"`
last_modified time.Time `json:"last_modified"`
}
// 允许在数据库中使用gorm模型与已存在的表:https://stackoverflow.com/questions/66318666/golang-gorm-how-to-create-a-model-for-an-existing-table
func (Era) TableName() string {
return "artwork_migrate_era"
}
我还在使用GIN进行请求处理:
func main() {
dsn := "...db_credentials..."
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect to db")
}
db.AutoMigrate(&Era{})
router := gin.Default()
router.GET("/era/:id", func(c *gin.Context) {
id := c.Param("id")
var era Era
db.Where("id = ?", id).Find(&era)
c.JSON(http.StatusOK, gin.H{
"Era": era.era_name,
})
})
router.Run("localhost:8080")
}
当我发出以下请求时: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:
type Era struct {
id int `json:"id"`
era_name string `json:"era_name"`
last_modified time.Time `json:"last_modified"`
}
// 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
func (Era) TableName() string {
return "artwork_migrate_era"
}
I'm also using GIN to make requests:
func main() {
dsn := "...db_credentials..."
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect to db")
}
db.AutoMigrate(&Era{})
router := gin.Default()
router.GET("/era/:id", func(c *gin.Context) {
id := c.Param("id")
var era Era
db.Where("id = ?", id).Find(&era)
c.JSON(http.StatusOK, gin.H{
"Era": era.era_name,
})
})
router.Run("localhost:8080")
}
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论