登录
首页 >  Golang >  Go问答

Gorm - 数据未被检索

来源:stackoverflow

时间:2024-03-10 08:12:25 267浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《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()
}

在我的 config/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 } 意味着实际上没有获取对象。我在这里缺少什么?


解决方案


gorm 使用 snake_case 来定义模型字段。 Link to docs

所以对于你的情况,基本上是:

package model

type Book struct {
    ID        int64  `json:"id" gorm:"primary_key"`
    Label     string `json:"label" gorm:"type:varchar(255)"`
}

我想您可以为 gorm 配置记录器,例如 https://gorm.io/docs/logger.html,以便能够在这些日志中查看实际的数据库查询。乍一看,您所做的一切都是正确的,如 https://gorm.io/docs/query.html#Retrieving-all-objects 中所述 但我个人遇到了一些不可预测的 gorm 行为,这在文档中并不那么明显

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>