Gorm - 不获取数据

我正在尝试使用Gin和Gorm设置REST API。以下是我的:main.go


package main


import (

    "app/config"

    "app/service"

    "github.com/gin-gonic/gin"

)


func main() {

    r := gin.Default()

    // Connect to database

    config.ConnectDatabase()

    r.GET("/books", service.FindBooks)

    // Run the server

    r.Run()

}

在我的,我试图像这样连接到DBconfig/setup.go


package config


import (

    "github.com/jinzhu/gorm"

    _ "github.com/jinzhu/gorm/dialects/mysql"

)


var DB *gorm.DB


// ConnectDatabase : Setup connection to database

func ConnectDatabase() {

    database, err := gorm.Open("mysql", "root:password@tcp(127.0.0.1:3306)/test_db")

    database.SingularTable(true)

    if err != nil {

        panic("Failed to connect to database!")

    }

    DB = database

}

在我的中,我有以下逻辑:service/book.go


package service


import (

    "errors"

    "app/config"

    "app/model"

    "fmt"

    "net/http"

    "github.com/gin-gonic/gin"

)


// FindBooks : Get all books

func FindBooks(c *gin.Context) {

    c.JSON(http.StatusOK, gin.H{"data": FindAllBooks()})

}


// FindAllBooks : Fetch all book from DB

func FindAllBooks() []model.Book {

    var book []model.Book

    config.DB.Find(&book)

    for i := 0; i < len(book); i++ {

        fmt.Println(book[i])

    }

    return book

}

而我的定义如下:model/Book.go


package model


type Book struct {

    id        int64  `json:"id" gorm:"primary_key"`

    label     string `json:"label" gorm:"type:varchar(255)"`

}

当我使用 运行应用程序时,以下是我可以看到的日志:go run main.go


[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.


[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.

 - using env:   export GIN_MODE=release

 - using code:  gin.SetMode(gin.ReleaseMode)


[GIN-debug] GET    /books                    --> feedconsumer/service.FindBooks (3 handlers)

[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default

[GIN-debug] Listening and serving HTTP on :8080

{0   }

[GIN] 2021/03/09 - 12:43:43 | 200 |    2.313864ms |             ::1 | GET      "/books"

基本上,这意味着对象实际上没有被获取。我在这里错过了什么?{0   }


慕码人2483693
浏览 152回答 2
2回答

守着一只汪

GORM用于定义模型字段。链接到文档snake_case因此,对于您的情况,它基本上是:package modeltype Book struct {&nbsp; &nbsp; ID&nbsp; &nbsp; &nbsp; &nbsp; int64&nbsp; `json:"id" gorm:"primary_key"`&nbsp; &nbsp; Label&nbsp; &nbsp; &nbsp;string `json:"label" gorm:"type:varchar(255)"`}

慕慕森

我想你可以像&nbsp;https://gorm.io/docs/logger.html&nbsp;一样为GORM配置记录器,以便能够在这些日志中看到实际的数据库查询。乍一看,您正在以正确的方式完成所有事情,如 https://gorm.io/docs/query.html#Retrieving-all-objects&nbsp;但我个人遇到了一些不可预测的GORM行为,这在文档中并不那么明显
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go