[英]Increment struct value in Go
我希望看到visits
隨着對/foo
每個GET
請求而增加,但它仍然為1
。 我在這里做錯了什么?
package main
import (
"log"
"github.com/gofiber/fiber/v2"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// Item model
type Item struct {
gorm.Model
UID int64 `gorm:"primaryKey;autoIncrement"`
Name string `gorm:"index;not null"`
Visits int32 `gorm:"default 0"`
}
func main() {
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic(err)
}
db.AutoMigrate(&Item{})
db.Create(&Item{
Name: "foo",
})
app := fiber.New(fiber.Config{})
app.Get("/:name", func(c *fiber.Ctx) error {
var i Item
db.First(&i, "name = ?", c.Params("name"))
if i.Name == "" {
return c.Status(fiber.StatusNotFound).JSON(&fiber.Map{
"message": "Not found",
})
}
db.Model(&i).Update("visits", i.Visits+1)
return c.JSON(i)
})
log.Println("Listening...")
log.Fatal(app.Listen(":3000"))
}
如果您記錄如下錯誤:
if err := db.Model(&i).Update("visits", i.Visits+1).Error; err != nil {
fmt.Printf("update err != nil; %v\n", err)
}
你會看到它說:“WHERE conditions required”。 所以,你可以解決這個問題:
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
定義為與gorm.Model
提供的內容沖突的Item
模型的一部分。 您可以在聲明模型中看到以下模型定義:
// 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 負載中注意到ID
和UID
都等於 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 自動將錯誤記錄到您的控制台,而無需像我建議的那樣專門處理它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.