| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- package user
- import (
- "fmt"
- . "prime/basic"
- "gorm.io/gorm"
- )
- type User struct {
- gorm.Model
- Username string `gorm:"not null;unique"`
- Password string `gorm:"not null"`
- Friends []*User `gorm:"many2many:user_friends;"`
- Profile Profile `gorm:"not null"`
- }
- type Profile struct {
- // ID uint `gorm:"primarykey"`
- UserID uint
- Name string
- Avatar string
- }
- func Migrate() {
- db := DB()
- db.AutoMigrate(&User{})
- db.AutoMigrate(&Profile{})
- // db.Create(&User{Username: "foo", Password: "bar"})
- }
- func Test() {
- db := DB()
- users := []User{
- {Username: "foo", Password: "bar"},
- {Username: "ignatz", Password: "password"},
- {Username: "alice", Password: "123"},
- {Username: "bob", Password: "123"},
- }
- users[0].Friends = []*User{&users[1], &users[2]}
- users[1].Friends = []*User{&users[0]}
- users[2].Friends = []*User{&users[0], &users[3]}
- users[3].Friends = []*User{&users[2]}
- // 1-2 1-3 3-4
- // db.Create(&users)
- db.Find(&users)
- // db.Create(&User{Username: "admin", Password: "admin", Friends: []*User{&users[0]}})
- // printUsers(users)
- // users[0].Friends = append(users[0].Friends, &users[1])
- // db.Where(&users[0]).Association("Friends").Append(&users[1])
- // db.Save(&users)
- for _, user := range users {
- var friends []User
- db.Model(&user).Association("Friends").Find(&friends)
- var friendsID []uint
- for _, friend := range friends {
- friendsID = append(friendsID, friend.ID)
- }
- fmt.Printf("#%d %s, friends=%v\n", user.ID, user.Username, friendsID)
- }
- }
|