从Golang结构中使用下划线访问MySQL字段

huangapple go评论87阅读模式
英文:

Access mysql field from golang struct with underscore

问题

我正在使用https://github.com/jinzhu/gorm库进行工作。由于某种原因,我无法访问我期望存在的某些字段。这些特定字段中包含下划线。例如,当我尝试访问SpeName时,它既不会失败也不会给我一个字符串。

type Specialties struct {
    SpeId      int64  
    SpeName    string 
    Conditions sql.NullString
    ParentId   sql.NullInt64 
    Hidden     sql.NullInt64
}

func IsFolderNameASpecialty(folderName string) models.Specialties {
    var sSpecialty models.Specialties
    for _, specialty := range Specialties {
        fmt.Println(strings.ToLower(folderName), specialty.SpeName)
        if strings.ToLower(folderName) == strings.ToLower(specialty.SpeName) {
            sSpecialty = specialty
        }
    }
    return sSpecialty
}

由于某种原因,println为空。MySQL字段实际上是spe_Name而不是SpeName。我应该使用什么标签来正确访问该字段?

英文:

I'm working with the https://github.com/jinzhu/gorm library. For some reason I can't access some fields that I expect to be there. Those particular fields have underscores in them. For instance when I try to Access SpeName it doesn't fail but it also does not give me a string

type Specialties struct {
	SpeId      int64  
	SpeName    string 
	Conditions sql.NullString
	ParentId   sql.NullInt64 
	Hidden     sql.NullInt64
}


func IsFolderNameASpecialty(folderName string) models.Specialties {
	var sSpecialty models.Specialties
	for _, specialty := range Specialties {
		fmt.Println(strings.ToLower(folderName), specialty.SpeName)
		if strings.ToLower(folderName) == strings.ToLower(specialty.SpeName) {
			sSpecialty = specialty
		}
	}
	return sSpecialty
}

For Some reason the println is empty. The mysql field is really spe_Name instead of SpeName. What tag do I use to allow me to access the field properly?

答案1

得分: 2

根据https://github.com/jinzhu/gorm#existing-schema,你想在结构体类型标签中使用column:

type Specialties struct {
    // ...
    SpeName    string `gorm:"column:spe_Name"`
    // ...
}
英文:

According to https://github.com/jinzhu/gorm#existing-schema, you want to use column: in the struct type tag.

type Specialties struct {
    // ...
    SpeName    string `gorm:"column:spe_Name"`
    // ...
}

huangapple
  • 本文由 发表于 2015年2月18日 07:24:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/28573167.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定