GORM:总是 return 空结果,即使记录存在

GORM : Always return empty results, even if records exists

我用了GORM.

我尝试按照文档中的示例进行操作。

我在 MySQL 数据库中有一个名为 "Attachements"

的 table

以下是我尝试获取所有记录的方式:

    type Attachements struct {
        reference int
        status int
        statusDate Timestamp
        path string
    }

func main() {

    db, err := gorm.Open(
        "mysql", 
        "root:passord@(localhost)/dwg_transformer?charset=utf8&parseTime=True&loc=Local"
    )

    if err!=nil {
        panic("Cannot connect to DB")
    }

    db.DB()
    db.DB().Ping()
    defer db.Close()

    atts := []Attachements{}

    db.Find(&atts)
    fmt.Println(atts)

}

我也试过了:

    rows, err := db.Model(&Attachements{}).Rows()
    defer rows.Close()

    if err != nil {
       panic(err)
    }

    att := Attachements{}

    for rows.Next() {
       db.ScanRows(rows, &att)
       fmt.Println(att)
    }

我也试过这样按列查询:

    db.Where(&Attachements{status: 0}).Find(&atts)

    for _, v := range atts {
    fmt.Println("reference : ", v.reference)
    fmt.Println("path : ", v.path)
    }

但在所有这种情况下,我得到的输出都是空的(没有打印,没有恐慌,没有错误!)

我试图以这种方式检索所有 table 的列表:

    tables := []string{}
    db.Select(&tables, "SHOW TABLES")
    fmt.Println(tables)

它输出我:[]

但是当我检查 "Attachements" table 是否存在时,它 returns 我 true :

    check:= db.HasTable("Attachements")
    fmt.Println(check)

我不明白我错过了什么(如果是的话)... 有什么想法吗?

非常感谢任何 GO 开发人员,我可能会遇到这里的问题...

Here is a screenshot of MySQL WorkBench : We can see the Attachements table and the rows

更新(20 年 3 月 3 日 19:00):

我尝试按照评论中的建议导出所有文件:

type Attachements struct {
    Reference int
    Status int
    StatusDate Timestamp
    Path string

   }

结果是一样的:所有测试都没有错误,输出为空。

更新(20 年 3 月 3 日 20:00):

我添加了一个 db.GetErrors(),因为正如评论中所建议的,GORM 不会自动报告错误:

[2020-03-03 19:58:05] Error 1146: Table 'dwg_transformer.attachements' doesn't exist

为什么我的 table 名字是小写的?

您的上一个错误表明 table 不存在。

引用自GORM: Conventions: Pluralized Table Name:

Table name is the pluralized version of struct name.

type User struct {} // default table name is `users`

// Set User's table name to be `profiles`
func (User) TableName() string {
  return "profiles"
}

因此 GORM 将为您的 Attachements 结构使用默认的 table 名称 attachements。要么将数据库中的 table 名称更改为此,要么提供一个 TableName() 方法,您可以在其中 return "Attachements",例如:

func (Attachements) TableName() string {
   return "Attachements"
}