Home > Blockchain >  Gorm only get only one records by using Find
Gorm only get only one records by using Find

Time:04-19

I'm trying to get all records from my DB, using Find to get condition records, here's my code

result := map[string]interface{}{}

conn = conn.Table("routeName")
conn = conn.Where("status = ?", 1)
conn = conn.Find(&result).Debug()

fmt.Println(result)

As using interface, I only get one row, result as following

map[id:1 routeName:FAFA status:1 routeCode:A]

I thought it's my interface's problem, so I tried using array as result, here's antoher define result

var result []model.RouteName

with this, I got following records

{[0    0][0    0]}

seen that my records data didn't put into result, to comfire that I did get row records from DB, Using count func to count records and result get 2, so I think that I do get records, but somehow I can't correctly get records value, following is my model

type RouteName struct {
    id           int    `gorm:"column:id" json:"id"`
    routeName    string `gorm:"column:routeName" json:"routeName"`
    status       int    `gorm:"column:status" json:"status"`
    routeCode    string `gorm:"column:routeCode" json:"routeCode"`
}

func (RouteName) TableName() string {
    return "routeName"
}

I have no idea that why it's work like this, need some advice to fix it.

CodePudding user response:

Gorm cannot access fields in your struct because they are not exported.

Exported identifiers

An identifier may be exported to permit access to it from another package. An identifier is exported if both:

  • the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
  • the identifier is declared in the package block or it is a field name or method name.

All other identifiers are not exported.

Before

type RouteName struct {
id           int    `gorm:"column:id" json:"id"`
routeName    string `gorm:"column:routeName" json:"routeName"`
status       int    `gorm:"column:status" json:"status"`
routeCode    string `gorm:"column:routeCode" json:"routeCode"`
}

After

type RouteName struct {
    Id           int    `gorm:"column:id" json:"id"`
    RouteName    string `gorm:"column:routeName" json:"routeName"`
    Status       int    `gorm:"column:status" json:"status"`
    RouteCode    string `gorm:"column:routeCode" json:"routeCode"`
}

CodePudding user response:

(Edit) Add some description for this answer.

GORM will use reflection to map each exported struct tag and write into the corresponding field. And unexported fields will be filtered out earlier here


I think you should try to publicize your struct fields.

type RouteName struct {
    ID           int    `gorm:"column:id" json:"id"`
    RouteName    string `gorm:"column:routeName" json:"routeName"`
    Status       int    `gorm:"column:status" json:"status"`
    RouteCode    string `gorm:"column:routeCode" json:"routeCode"`
}
  • Related