package main import ( "fmt" "gorm.io/driver/sqlite" "gorm.io/gorm" ) // 学生和课程:多对多关系 type Student struct { ID uint `gorm:"primaryKey"` Name string `gorm:"size:100"` Courses []Course `gorm:"many2many:student_courses;"` // 多对多 } type Course struct { ID uint `gorm:"primaryKey"` Name string `gorm:"size:100"` Students []Student `gorm:"many2many:student_courses;"` // 多对多 } func main() { db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) //db.AutoMigrate(&Student{}, &Course{}) // 1. 创建课程 //math := Course{Name: "Math"} //physics := Course{Name: "Physics"} //chemistry := Course{Name: "Chemistry"} //db.Create(&math) //db.Create(&physics) //db.Create(&chemistry) // 2. 创建学生并关联课程 //alice := Student{ // Name: "Alice", // Courses: []Course{math, physics}, //} //bob := Student{ // Name: "Bob", // Courses: []Course{physics, chemistry}, //} //db.Create(&alice) //db.Create(&bob) //fmt.Println("Students and courses created") //查询数据库的alice的学生 var alice Student db.Where("name = ?", "Alice").First(&alice) //查询数据库的Bob学生 var bob Student db.Where("name = ?", "Bob").First(&bob) //查询课程 var math Course db.Where("name = ?", "Math").First(&math) //// 5. 添加关联 //db.Model(&alice).Association("Courses").Append(&chemistry) //fmt.Println("Alice enrolled in Chemistry") //// 7. 替换所有关联 //db.Model(&alice).Association("Courses").Replace(&math) //fmt.Println("Alice now only takes Math") // 8. 清空关联 db.Model(&bob).Association("Courses").Clear() fmt.Println("Bob dropped all courses") // 3. 查询学生的课程 var student1 Student db.Preload("Courses").First(&student1, 1) fmt.Printf("%s's courses:\n", student1.Name) for _, course := range student1.Courses { fmt.Printf(" - %s\n", course.Name) } // 4. 查询课程的学生 var course1 Course db.Preload("Students").First(&course1, 1) fmt.Printf("%s course students:\n", course1.Name) for _, student := range course1.Students { fmt.Printf(" - %s\n", student.Name) } //查询bob的课程 var student2 Student db.Preload("Courses").First(&student2, 2) fmt.Printf("%s's courses:\n", student2.Name) for _, course := range student2.Courses { fmt.Printf(" - %s\n", course.Name) } }