Skip to content

Instantly share code, notes, and snippets.

@sempr
Created January 18, 2021 23:40
Show Gist options
  • Save sempr/dc48f0ae9982899792ab5a1c0588362d to your computer and use it in GitHub Desktop.
Save sempr/dc48f0ae9982899792ab5a1c0588362d to your computer and use it in GitHub Desktop.
Relations Demo
package main
import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type Student struct {
gorm.Model
Name string
Parents []Parent `gorm:"many2many:relations;"`
}
type Parent struct {
gorm.Model
Name string
}
type Relation struct {
StudentID uint `gorm:"primaryKey"`
ParentID uint `gorm:"primaryKey"`
Relation string
}
func main() {
st1 := Student{Name: "朱高炽"}
st2 := Student{Name: "朱玉英"}
st3 := Student{Name: "徐景昌"}
pa1 := Parent{Name: "朱元璋"}
pa2 := Parent{Name: "马秀英"}
pa3 := Parent{Name: "徐达"}
pa4 := Parent{Name: "徐增寿"}
pa5 := Parent{Name: "朱棣"}
pa6 := Parent{Name: "徐氏"}
db, err := gorm.Open(sqlite.Open("relations.db"), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
panic(err)
}
db.AutoMigrate(&Student{}, &Parent{}, &Relation{})
db.Create(&st1)
db.Create(&st2)
db.Create(&st3)
db.Create(&pa1)
db.Create(&pa2)
db.Create(&pa3)
db.Create(&pa4)
db.Create(&pa5)
db.Create(&pa6)
fmt.Println(st1)
db.Create(&Relation{StudentID: st1.ID, ParentID: pa1.ID, Relation: "爷爷"})
db.Create(&Relation{StudentID: st1.ID, ParentID: pa2.ID, Relation: "奶奶"})
db.Create(&Relation{StudentID: st1.ID, ParentID: pa5.ID, Relation: "爸爸"})
db.Create(&Relation{StudentID: st1.ID, ParentID: pa6.ID, Relation: "妈妈"})
db.Create(&Relation{StudentID: st2.ID, ParentID: pa1.ID, Relation: "爷爷"})
db.Create(&Relation{StudentID: st2.ID, ParentID: pa2.ID, Relation: "奶奶"})
db.Create(&Relation{StudentID: st2.ID, ParentID: pa5.ID, Relation: "爸爸"})
db.Create(&Relation{StudentID: st2.ID, ParentID: pa6.ID, Relation: "妈妈"})
db.Create(&Relation{StudentID: st3.ID, ParentID: pa3.ID, Relation: "爷爷"})
db.Create(&Relation{StudentID: st3.ID, ParentID: pa4.ID, Relation: "爸爸"})
db.Create(&Relation{StudentID: st1.ID, ParentID: pa3.ID, Relation: "外公"})
db.Create(&Relation{StudentID: st2.ID, ParentID: pa3.ID, Relation: "外公"})
}
/*
> select students.id, students.name, relations.relation, parents.id, parents.name from students join relations on students.id=relations.student_id join parents on parents.id = relations.parent_id where parents.id=3;
3|徐景昌|爷爷|3|徐达
1|朱高炽|外公|3|徐达
2|朱玉英|外公|3|徐达
> select students.id, students.name, relations.relation, parents.id, parents.name from students join relations on students.id=relations.student_id join parents on parents.id = relations.parent_id where students.id=1;
1|朱高炽|爷爷|1|朱元璋
1|朱高炽|奶奶|2|马秀英
1|朱高炽|外公|3|徐达
1|朱高炽|爸爸|5|朱棣
1|朱高炽|妈妈|6|徐氏
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment