我用过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 开发人员可能会遇到这里的问题......这是 MySQL WorkBench 的屏幕截图:我们可以看到 Attachements 表和行更新(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为什么我的表的名称是小写的?
1 回答

函数式编程
TA贡献1807条经验 获得超9个赞
您的最后一个错误表明该表不存在。
引用GORM:约定:复数表名:
表名是结构名的复数形式。
type User struct {} // default table name is `users`
// Set User's table name to be `profiles`
func (User) TableName() string {
return "profiles"
}
attachements所以 GORM 将为你的Attachements结构使用默认的表名。将数据库中的表名更改为此,或提供TableName()返回的方法"Attachements",例如:
func (Attachements) TableName() string {
return "Attachements"
}
- 1 回答
- 0 关注
- 135 浏览
添加回答
举报
0/150
提交
取消