简体   繁体   English

Golang(GIN 框架):GORM 查询不起作用

[英]Golang (GIN Framework) : GORM Query didnt work

Sorry for asking such a dumb question.抱歉问了这么蠢的问题。 I just learn golang several days ago.前几天刚学golang。

And I want to build API Services with GIN Framework.我想用 GIN 框架构建 API 服务。 I use Jinzhu gorm for query mysql database.我使用 Jinzhu gorm 查询 mysql 数据库。

The problem is, my query result always null.问题是,我的查询结果始终为空。

This is my code:这是我的代码:

Model folder:模型文件夹:

package models

import "github.com/jinzhu/gorm"

type (
    User struct {
        gorm.Model
        Name    string `json:"name"`
        Phone   string `json:"phone"`
        Address string `json:"address"`
        Age     int    `json:"age"`
        Gender  string `json:"gender"`
    }
)

Resource folder:资源文件夹:

package resources

import (

    // Standard library packages
    "net/http"

    // Third party packages
    "../models"
    "github.com/gin-gonic/gin"
    "github.com/jinzhu/gorm"
)

type (
    UserResource struct {
        db *gorm.DB
    }
)

func NewUserResource(s *gorm.DB) *UserResource {
    return &UserResource{s}
}

func (ur UserResource) Index(c *gin.Context) {
    var users []models.User

    ur.db.Find(&users)
    if len(users) <= 0 {
        c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "error": "not found"})
        return
    }

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

And the last is controller folder:最后是控制器文件夹:

package controllers

import (
    "../resources"
    "github.com/gin-gonic/gin"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

type UserService struct {
}

func Database() *gorm.DB {
    //open a db connection
    db, err := gorm.Open("mysql", "root:root@/insp?charset=utf8&parseTime=True&loc=Local")
    if err != nil {
        panic("failed to connect database")
    }

    return db
}

func (s *UserService) Run() {
    // Instantiate a new router
    router := gin.Default()
    v1 := router.Group("/api/v1/users")
    {
        db := Database()
        us := resources.NewUserResource(db)
        v1.GET("/", us.Index)
    }
    router.Run(":9090")
}

everytime I hit the endpoint to get list of users, the result always return user not found.每次我点击端点获取用户列表时,结果总是返回找不到用户。

But When I change into Raw query, it works well但是当我更改为原始查询时,它运行良好

ur.db.Raw("SELECT * FROM users").Scan(&users)

I already try to read the GORM docs.我已经尝试阅读 GORM 文档。

anyone know how to fix it?有谁知道如何解决它?

Thanks for advice谢谢你的建议

If your code has database connection error try to add some logger.如果您的代码有数据库连接错误,请尝试添加一些记录器。 I usually use logrus logger:我通常使用logrus记录器:

newLogger := logger.New(
    config.Log,
    logger.Config{
        SlowThreshold: time.Second,
        LogLevel:      logger.Error,
        Colorful:      false,
    },
)

and configure logger with gorm connection line并使用 gorm 连接线配置记录器

database, err := gorm.Open("root:root@/insp?charset=utf8&parseTime=True&loc=Local", &gorm.Config{Logger: newLogger})

On production version I recommended use Error log level, but in debug mode you can use Info log level to see SQL queries to db.在生产版本上,我建议使用错误日志级别,但在调试模式下,您可以使用信息日志级别查看对数据库的 SQL 查询。

And I think I am using newer version than Question author.而且我认为我使用的版本比问题作者更新的版本。 Sorry if that.对不起,如果那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM