1.多对多关系的定义
type Student struct {
gorm.Model
Code string
Name string
Books []Book `gorm:"many2many:student_books;"`
}
type Book struct {
gorm.Model
Name string
Students []Student `gorm:"many2many:student_books;"`
}
注意:我刚开始加了json相关的信息,这个联结表就没有生成( json: "books" gorm:"many2many:student_books;")
切记gorm:跟many2many之间不能有空格,否则联结表不会生成。定义了模型以后,只要调用db.AutoMigrate(&Student{}, &Book{})会生成三张表。
mysql> show tables;
+-----------------------------------+
| Tables_in_gorm |
+-----------------------------------+
| books |
| student_books |
| students |
+-----------------------------------+
2.多对多数据的插入
有两种方式:
2.1 直接在数据定义的时候指定。
s