Created
July 11, 2023 19:21
-
-
Save alirezaarzehgar/f6026a16263cc6b86c71d0d68cd6eae0 to your computer and use it in GitHub Desktop.
Self-Referential Has One in GORM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "log" | |
| "gorm.io/driver/sqlite" | |
| "gorm.io/gorm" | |
| ) | |
| type User struct { | |
| ID uint | |
| Name string | |
| ManagerID *uint | |
| Manager *User | |
| } | |
| func main() { | |
| db, err := gorm.Open(sqlite.Open("name.db")) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| if db.Migrator().HasTable(&User{}) { | |
| db.Migrator().DropTable(&User{}) | |
| } | |
| db.AutoMigrate(&User{}) | |
| names := []string{"Ali", "Reza", "Hamid", "Amin", "Sadegh", "Hashem"} | |
| var u *User = &User{} | |
| up := u | |
| for _, name := range names { | |
| u.Manager = &User{Name: name} | |
| u = u.Manager | |
| } | |
| db.Create(up) | |
| u = &User{} | |
| for u != nil { | |
| db.Preload("Manager").Find(&u, len(names)) | |
| fmt.Println(*u) | |
| u = u.Manager | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment