'How to set lower or upper in gorm model when primary key is mixed
I have a table with 3 columns:
- emrID (this is the primary key)
- patient_name (string)
- Comment(string)
This my code
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
)
type Patient_List struct {
Patient_name string
EmrID string `gorm:"primaryKey"`
Comment string
}
func Main() {
var onePatient Patient_List
db, err := gorm.Open(sqlite.Open("E://sqlitDB//test.db"), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
})
db.Find(&onePatient, "Comment=?", "has Tag with emrID")
if err != nil {
fmt.Printf("connect err", err)
} else {
fmt.Printf(onePatient.Patient_name)
fmt.Printf(onePatient.EmrID)
}
}
I got a record onePatient
, the onePatient.Patient_name
has a value, but onePatient.EmrID
is empty.
When I change table columns emrID
to emrid
, and change the code to this:
type Patient_List struct {
Patient_name string
Emrid string `gorm:"primaryKey"` // EmrID->Emrid
Comment string
}
it can get data in onePatient.EmrID
. So if I don't change my table columns, what change in code can make onePatient.EmrID
has data?
I test some types like
- table: emrID ; struct: Emr_id
- table: emrID ; struct: Emr_ID
- table: emrID ; struct: EmrID
but all of those do not work
Solution 1:[1]
If the column names in your database is not in snake-case,then you need to explicitly tell the name of your columns to GORM. For that purpose, you can use the tags when you are creating your struct. In your case you can do the following:
type Patient_List struct {
Patient_name string `gorm:"column:patient_name" json:"patient_name"`
Emrid string `gorm:"primaryKey; column:emr_id"`
Comment string `gorm:"column:comment" json:"comment"`
}
GORM only expects column names with snake case by default. So that, if you want to have column names with for example camel-case or kebab-case, then you have to write those tags in your model.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tural Abdulsamad |