1 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超10個(gè)贊
如果您記錄以下錯(cuò)誤:
if err := db.Model(&i).Update("visits", i.Visits+1).Error; err != nil {
fmt.Printf("update err != nil; %v\n", err)
}
你會(huì)看到它說:“需要條件”。所以,你可以像這樣解決這個(gè)問題:
if err := db.Model(&i).Where("name = ?", i.Name).Update("visits", i.Visits+1).Error; err != nil {
fmt.Printf("update err != nil; %v\n", err)
}
這是有關(guān)GORM 中的錯(cuò)誤處理的更多詳細(xì)信息
編輯:您的示例實(shí)際上存在一個(gè)更大的問題。問題是您將其定義UID為Item模型的一部分,這與提供的內(nèi)容沖突gorm.Model。您可以在聲明模型中看到以下模型定義:
// gorm.Model definition
type Model struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
}
當(dāng)添加到您的Item類型/模型中時(shí),您將獲得:
type Item struct {
// gorm.Model
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
// your fields
UID int64 `gorm:"primaryKey;autoIncrement"`
Name string `gorm:"index;not null"`
Visits int32 `gorm:"default 0"`
}
似乎這會(huì)導(dǎo)致您的數(shù)據(jù)庫(kù)表以奇怪的狀態(tài)創(chuàng)建。您可能會(huì)在返回的 JSON 有效負(fù)載中注意到IDANDUID都等于 0。當(dāng)您多次啟動(dòng)/停止服務(wù)器并查看創(chuàng)建的其他記錄(因?yàn)槟鷇b.Create()位于頂部)時(shí),您最終會(huì)得到多個(gè)項(xiàng)目名稱為“foo”,所有的ID和UID都為 0...這就是為什么 GORM 在沒有 WHERE 子句的情況下無法更新項(xiàng)目的原因,因?yàn)橹麈I沒有在表上正確設(shè)置。
如果您從模型中刪除 UID(或者甚至只是從中刪除“primaryKey”),則可以使用該Update()方法而無需 where 條件。因此,您的模型應(yīng)如下所示:
// Item model
type Item struct {
gorm.Model
Name string `gorm:"index;not null"`
Visits int32 `gorm:"default 0"`
}
更改模型/類型后,請(qǐng)確保刪除test.db文件,以便使用新/正確格式重新創(chuàng)建表。
最后,關(guān)于我的原始答案,您還應(yīng)該看到 GORM 自動(dòng)將錯(cuò)誤記錄到您的控制臺(tái),而無需像我建議的那樣專門處理它們。
- 1 回答
- 0 關(guān)注
- 120 瀏覽
添加回答
舉報(bào)