1 回答

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