GORM 似乎自己伪造了 table 个名字

GORM seems to fabricate table names on it's own

我有一个 gorilla/mux 站点,我需要使用 GORM 来处理数据库。

首先,我只是想像 hello world 一样看看我是否可以访问数据库。

所以有如下代码:

type user struct {
    user_id  int
    username string
    email    string
    pw_hash  string
}

func gormo(w http.ResponseWriter, r *http.Request) {

    db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    var user user
    db.Find(&user)

    fmt.Println(user)

}

现在,数据库有一个名为 table 的用户,我只想从中返回一些东西。当此代码为 运行 时,出现以下命令行错误:

no such table: users
[0.217ms] [rows:0] SELECT * FROM `users`

这很奇怪,在我的代码中没有任何地方有任何名为 'users' 的东西,我的数据库也没有。 这个 s 从哪里来,为什么 GORM 似乎要把它放在那里?

您的数据库中还没有任何内容。好吧,无论如何,GORM 没有创建任何东西。您需要先migrate。这将创建您的 table。你可以这样做:

db.AutoMigrate(&user{})

此外,GORM 更喜欢约定而不是配置,它pluralizes table names by default。因此,创建 table 后,其名称将为 users.

编辑:您可能需要通过将名称大写来使您的结构及其字段在外部可见。