GORM:即使记录存在,也总是返回空结果

问题描述 投票:0回答:1

我使用了GORM(Golang最受欢迎的ORM之一)

我尝试遵循文档上的示例。

我在MySQL DB中有一个名为“附件”的表

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

    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)
    }

但是在所有情况下,我的输出都是空的(没有打印,没有紧急情况,没有错误!)

我试图以此方式检索所有表的列表:

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

输出我:[]

但是当我检查“附件”表是否存在时,它将返回我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

更新(03/03/20 19:00):

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

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

   }

结果是相同的:所有测试均无错误,并且输出为空。

UPDATE(03/03/20 20:00):

我添加了db.GetErrors(),因为注释中建议,GORM不会自动报告错误:

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

为什么我的表使用小写名称?

mysql go orm gorm
1个回答
0
投票

您的上一个错误指示该表不存在。

GORM: Conventions: Pluralized Table 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结构使用默认的表名Attachements。可以将数据库中的表名更改为此,或者提供TableName()方法,在该方法中您返回"Attachements",例如:]

func (Attachements) TableName() string {
   return "Attachements"
}
© www.soinside.com 2019 - 2024. All rights reserved.