我正在使用GORM连接到我的数据库.我使用的是GoFibre的应用程序.我有两个端点,一个是列出所有房间的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

接口输出:-

{
  "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": ""
    }
  ]
}

Update:- 01/20/2024
当我切换到Postgres数据库时,这个代码可以正常工作.所以我要换成Postgres,然后 checkout .

推荐答案

我使用以下代码进行了快速测试:

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()
}

这就是我得到的:

{
  "rooms":[
    {
      "ID":1,
      "CreatedAt":"2024-01-19T15:54:10.19868+03:00",
      "UpdatedAt":"2024-01-19T15:54:10.19868+03:00",
      "DeletedAt":null,
      "room_type":"single"
    },
    {
      "ID":2,
      "CreatedAt":"2024-01-19T15:54:10.199816+03:00",
      "UpdatedAt":"2024-01-19T15:54:10.199816+03:00",
      "DeletedAt":null,
      "room_type":"King Size Bed"
    },
    {
      "ID":3,
      "CreatedAt":"2024-01-19T15:55:07.110176+03:00",
      "UpdatedAt":"2024-01-19T15:55:07.110176+03:00",
      "DeletedAt":null,
      "room_type":"Twin Bed"
    },
    {
      "ID":4,
      "CreatedAt":"2024-01-19T15:55:07.115137+03:00",
      "UpdatedAt":"2024-01-19T15:55:07.115137+03:00",
      "DeletedAt":null,
      "room_type":"Deluxe bed"
    }
  ]
}

Go相关问答推荐

Go:嵌入类型不能是类型参数""

为什么工具链指令在这种情况下没有效果?

如何将文件从AWS S3存储桶复制到Azure BLOB存储

如何使用中间件更改http请求的响应代码?

Golang String

在nixos上找不到XInput2.h头文件的包

Golang:访问any类型泛型上的字段

Go安装成功但没有输出简单的Hello World

使用Cookie身份验证的Gorilla Golang Websocket优化

如何在 Go 中将 int 转换为包含 complex128 的泛型类型?

我的神经网络(从头开始)训练,让它离目标更远

使用 Grafana alert 在几分钟内重复alert

如何在golang中按字符a对字符串数组进行排序

为什么 0 big.Int 的 .Bytes() 值是空切片?

关系不存在 GORM

Golang ACMEv2 HTTP-01 挑战不挑战服务器

如何在 docker 文件中安装 golang 包?

在 Go 中表达函数的更好方法( struct 方法)

Go 错误处理、类型断言和 net package包

全局记录(across packages)