I started to learn go few days ago, and I'm trying to build a REST API using go and gorm for data persistence. I'm building a movie management API and I have some Profile that take Qualities and Language associations.
type Profile struct {
gorm.Model
ThresholdQuality Quality `json:"thresholdQuality" validate:"required"`
PreferredLanguage Language `json:"preferredLanguage" validate:"required"`
}
type Language struct {
Language string `json:"language" gorm:"primary_key"`
}
type Quality struct {
Quality string `json:"quality" gorm:"primary_key"`
}
and the creation in the Database
func InitDb(){
var err error
DB, err = gorm.Open("sqlite3", "gotorro.db")
if err != nil {
fmt.Printf("%s",err)
panic("failed to connect database.")
}
DB.AutoMigrate(&Movie{})
DB.AutoMigrate(&Quality{})
DB.AutoMigrate(&Language{})
DB.AutoMigrate(&Profile{})
french := Language{Language:"french"}
english := Language{Language:"english"}
DB.Create(&french)
DB.Create(&english)
profile := Profile{
ThresholdQuality: Quality{"1080p"},
PreferredLanguage: Language{"french"},
}
DB.Create(&profile)
}
when looking to my database though sqlite the languages and qualities are sucessfully created
sqlite> select * from qualities ;
1080p
720p
sqlite> select * from Languages ;
french
english
but when my profile is created qualities and language remain empty
sqlite> select * from profiles;
12|2019-07-25 09:54:44.165365026-04:00|2019-07-25 09:54:44.165365026-04:00|||||
According to the gorm documentation, my profile should contain foreign key to quality and language.
What am I missing there ?
In your profiles model you need to create field which will store the foreignkey of releated model. So your profile model should look like
type Profile struct {
gorm.Model
ThresholdQuality Quality `json:"thresholdQuality" validate:"required"`
ThresholdQualityQuality string
PreferredLanguage Language `json:"preferredLanguage" validate:"required"`
PreferredLanguageLanguage string
}
By default gorm uses field name for releation composed from FieldName in Profile model (in you case eg. TresholdQuality) and name of primary key field in associated model (for Quality struct is Quality field). You can change that by using gorm:"foreignkey"
tag then your profile can look like this
type Profile struct {
gorm.Model
ThresholdQuality Quality `gorm:"foreignkey:ThresholdQualityID" json:"thresholdQuality" validate:"required"`
ThresholdQualityID string
PreferredLanguage Language `gorm:"foreignkey:PreferredLanguageID" json:"preferredLanguage" validate:"required"`
PreferredLanguageID string
}