0
votes

Sorry for asking such a dumb question. I just learn golang several days ago.

And I want to build API Services with GIN Framework. I use Jinzhu gorm for query mysql database.

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.

anyone know how to fix it?

Thanks for advice

1
You need to check the result reported by gorm error. err := ur.db.Find(&users).ErrorBogdan Iulian Bursuc
@BogdanIulianBursuc no error, I already checked it twiceCode On
You could try enabling debug for that query and see what gorm is trying to create as SQL: ur.db.Debug().Find(&users)Bogdan Iulian Bursuc
@BogdanIulianBursuc thankyou, so the query try to select where deleted_at is null, and my deleted_at value is not null. thankyouCode On
Maybe you use the SoftDelete functionality? Read here: jinzhu.me/gorm/crud.html#deleteBogdan Iulian Bursuc

1 Answers

0
votes

If your code has database connection error try to add some logger. I usually use logrus logger:

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

and configure logger with gorm connection line

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.

And I think I am using newer version than Question author. Sorry if that.