登录
首页 >  Golang >  Go问答

从现存表格中使用GORM返回空字符串

来源:stackoverflow

时间:2024-02-07 19:27:22 427浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《从现存表格中使用GORM返回空字符串》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我在 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"`
}

// 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"
}

我还使用 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":""}

我只是错过了一些明显的东西吗?


正确答案


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

理论要掌握,实操不能落!以上关于《从现存表格中使用GORM返回空字符串》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>