I would like to save the following structures in the form of multiple teachers in one LectureInfo.
typeLectureInfoct{
gorm.Model
Name string
Teachers[] Teacher `gorm: "foreignKey:LectureID"`
}
typeTeacher structure {
gorm.Model
LectureID string
// Abbreviated below
}
You register LectureInfo first and add Teacher later, but the Teacher is not successfully added to LectureInfo.Teachers.
First of all, the database initialization is as follows:
funclidbInit(){
db,err: =gorm.Open("sqlite3", "rectureInfo.sqlite3")
db.AutoMigrate (&LectureInfo{}, & Teacher{}/*, & EvaluationMethod{}, & RequiredKnowledge{}, & Comment{}*/)
prefer db.Close()
}
Next, registering for LectureInfo is as follows.
funclidbInsertLecture(rectureName string, teachers[]Teacher){
db: =gorm.Open("sqlite3", "rectureInfo.sqlite3")
db.Create (&LectureInfo {Name:lectureName, Teachers:teachers})
prefer db.Close()
}
This is the last addition of teacher
//add teacher ID
funclidbAddTeacher(rectureID string, teacherTeacher){
db: =gorm.Open("sqlite3", "rectureInfo.sqlite3")
variableInfo LectureInfo
db.First (&rectureInfo,rectureID)
teachInfo.Teachers=append(lectureInfo.Teachers, teacher)
/////////////////
fmt.Println (rectureInfo.Teachers)
/////////////////
db.Save (&lectureInfo)
db.Close()
}
If you added it correctly, you should see two teachers on the console in the list (enclosed by //), but you could only add one teacher on the second addition (I thought I registered in Fuji, Gokami, but only Gokami instead of Fuji, Gokami).
Also, when I try to get LectureInfo with the code below, LectureInfo.Teachers is empty slice
funclidbGetOne(id int)LectureInfo{
db: =gorm.Open("sqlite3", "rectureInfo.sqlite3")
variableInfo LectureInfo
db.First (&lectureInfo,id)
db.Close()
return noteInfo
}
This is probably due to my lack of understanding of SQL, but could you tell me how to add teachers correctly?
go gorm
At first glance, the second teacher addition does not seem to work because the teachers table is not preloaded in the db.First(&lectureInfo,id)
section.For this reason, lectureInfo.Teachers
immediately after db.First
is []
.
Instead,
db.Preload("Teachers").First(&lectureInfo,id)
It also queries data from a separate table associated with Has Many and brings it to you. Check the value of lectureInfo.Teachers
or query the DB client directly to list the records to see how it behaves.Learn more: https://gorm.io/docs/preload.html
By the way, when you add records to a Has Many-related table like this, GORM has its own function: https://gorm.io/docs/associations.html#Append-Associations
db.Model(&lectureInfo).Association("Teachers").Append(&teacher)
With this, you don't have to bother loading existing teachers.
Pointing out that is not relevant to the subject:This time Teachers
LectureID
is of type string
, but ID
of LectureInfo
is of type uint
, so if you don't have any particular intention, it's natural to match the type uint
.
© 2024 OneMinuteCode. All rights reserved.