亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

GORM :即使存在記錄,也總是返回空結果

GORM :即使存在記錄,也總是返回空結果

Go
一只萌萌小番薯 2022-05-18 16:37:24
我用過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)    }但在所有這種情況下,我得到了空輸出(沒有打印,沒有恐慌,沒有錯誤?。┪以噲D以這種方式檢索所有表的列表:    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"

}


查看完整回答
反對 回復 2022-05-18
  • 1 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號