首頁  >  文章  >  後端開發  >  GORM Find(&room) 操作用空資料而非實際資料填入結構

GORM Find(&room) 操作用空資料而非實際資料填入結構

王林
王林轉載
2024-02-08 22:10:08897瀏覽

GORM Find(&room) 操作用空数据而不是实际数据填充结构

php小編小新發現,使用GORM的Find(&room)操作時,有時會出現使用空資料填充結構的情況,而不是使用實際資料。這可能導致程式出現錯誤或異常。為了解決這個問題,我們需要了解GORM的工作原理以及如何正確使用Find操作來填充結構,從而避免這種情況的發生。在本文中,我們將詳細介紹這個問題的原因,並提供解決方案來確保正確使用GORM的Find操作。

問題內容

我正在使用 GORM 連接到我的資料庫。我正在使用 GoFiber 作為該應用程式。我有兩個端點,一個用於列出所有房間的 GET 和一個用於創建房間的 POST。我正在使用 Gorm MySQL 驅動程式並連接到 PlanetScale 託管的資料庫。

我的模型:-

type Room struct {
    Model
    RoomType string `json:"room_type" validate:"required"`
}

我的取得端點程式碼:-

func GetAllRooms(c *fiber.Ctx) error {
    var rooms []entities.Room

    res := database.Database.Find(&rooms)
    
    if res.RowsAffected != 0 {
        return c.JSON(fiber.Map{"rooms": rooms})
    } else {
        return c.JSON(fiber.Map{"rooms": nil})
    }
}

我的資料庫程式碼:-(託管在planetscale)

var Database *gorm.DB

func ConnectDb() {
    dsn := "sample_dsn/mydatabase?tls=true&interpolateParams=true"
    db, err := gorm.Open(mysql.Open(dsn))
    if err != nil {
        panic("Failed to connect to DB")
    }
    // Setup Migrations Here
    db.AutoMigrate(&entities.Booking{})
    db.AutoMigrate(&entities.Inventory{})
    db.AutoMigrate(&entities.Room{})
    db.AutoMigrate(&entities.User{})
    Database = db
}

控制台輸出:-

{{1 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC {0001-01-01 00:00:00 +0000 UTC false}} }
{{2 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC {0001-01-01 00:00:00 +0000 UTC false}} }
{{3 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC {0001-01-01 00:00:00 +0000 UTC false}} }
{{4 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC {0001-01-01 00:00:00 +0000 UTC false}} }

資料庫中的資料:-

id       created_at              updated_at          deleted_at      **room_type**
1   2024-01-18 19:27:36.680   2024-01-18 19:27:36.680                 DOUBLE_ROOM
2   2024-01-18 19:27:41.206   2024-01-18 19:27:41.206                 DOUBLE_ROOM
3   2024-01-18 19:27:49.403   2024-01-18 19:27:49.403                 KING_SIZE_AC
4   2024-01-19 11:06:11.789   2024-01-19 11:06:11.789                 DOUBLE_BED

API 輸出:-

{
  "rooms": [
    {
      "ID": 1,
      "CreatedAt": "0001-01-01T00:00:00Z",
      "UpdatedAt": "0001-01-01T00:00:00Z",
      "DeletedAt": null,
      "room_type": ""
    },
    {
      "ID": 2,
      "CreatedAt": "0001-01-01T00:00:00Z",
      "UpdatedAt": "0001-01-01T00:00:00Z",
      "DeletedAt": null,
      "room_type": ""
    },
    {
      "ID": 3,
      "CreatedAt": "0001-01-01T00:00:00Z",
      "UpdatedAt": "0001-01-01T00:00:00Z",
      "DeletedAt": null,
      "room_type": ""
    },
    {
      "ID": 4,
      "CreatedAt": "0001-01-01T00:00:00Z",
      "UpdatedAt": "0001-01-01T00:00:00Z",
      "DeletedAt": null,
      "room_type": ""
    }
  ]
}

更新:- 01/20/2024

當我切換到 Postgres 資料庫時,這個確切的程式碼可以運作。所以我改用 Postgres 並關閉此票。

解決方法

我使用以下程式碼進行了快速測試:

package main

import (
    "github.com/gofiber/fiber/v2"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
    "log"
)

var (
    dsn = "host=localhost user=postgres password=secret dbname=mySampleDb port=5432 sslmode=disable"
)

type Room struct {
    gorm.Model
    RoomType string `json:"room_type" validate:"required"`
}

var DB *gorm.DB

func main() {
    initDb()
    app := fiber.New()

    app.Get("/", getAllRoomsForFiber)

    app.Listen(":3000")
}
func getAllRoomsForFiber(c *fiber.Ctx) error {
    var rooms []Room
    res := DB.Find(&rooms)
    if res.RowsAffected != 0 {
        return c.JSON(fiber.Map{"rooms": rooms})
    } else {
        return c.JSON(fiber.Map{"rooms": nil})
    }
}

func seedDb() {
    DB.Create(&Room{RoomType: "single"})
    DB.Create(&Room{RoomType: "Deluxe bed"})
    DB.Create(&Room{RoomType: "Twin bed"})
    DB.Create(&Room{RoomType: "King Size bed"})
}
func initDb() {
    db, err := gorm.Open(postgres.Open(dsn))
    if err != nil {
        log.Fatal("couldn't connect to db")
    }
    DB = db
    db.AutoMigrate(&Room{})
    seedDb()
}

這就是我得到的:

德巴4139f5302207be648f12c74de60e

以上是GORM Find(&room) 操作用空資料而非實際資料填入結構的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除