【问题标题】:GORM : Always return empty results, even if records existsGORM :即使存在记录,也总是返回空结果
【发布时间】:2020-06-16 02:26:03
【问题描述】:

我用GORM

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

我在 MySQL 数据库中有一个名为“附件”的表

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

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

我尝试按照 cmets 中的建议导出所有文件,如下所示:

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

   }

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

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

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

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

为什么我的表格名称是小写的?

【问题讨论】:

  • 我试过..同样的结果(没有输出,也没有错误)
  • 感谢 @icza 的 cmets。我更新了帖子。 db.Find(&att) 不返回任何错误,但实际上是空切片 []
  • 实际上使用gorm,你必须调用db.GetErrors(),它不会在发生错误时返回。请在最后检查一下。
  • 这很重要:当我运行db.GetErrors() 时,我得到了[2020-03-03 19:58:05] Error 1146: Table 'dwg_transformer.attachements' doesn't exist
  • 那就先创建吧。

标签: mysql go orm go-gorm


【解决方案1】:

您的最后一个错误表明该表不存在。

引用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"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多