我有一个自引用的结构,当我尝试使用Preload
来获取数据时,记录会以某种方式在父级和子级之间切换。
在此示例中,我创建了以下记录:
代码如下:
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
type Person struct {
ID int `gorm:"primary_key"`
Name string
Parent int
Parent_ *Person `gorm:"foreignkey:parent"`
}
func (Person) TableName() string {
return "go_person"
}
const (
DB_ADAPTER = "postgres"
DB_HOST = "localhost"
DB_USER = "postgres"
DB_PASSWORD = "test"
DB_NAME = "test"
DB_SSLMODE = "disable"
)
func main() {
db, err := gorm.Open(DB_ADAPTER, "host="+DB_HOST+" user="+DB_USER+" dbname="+DB_NAME+" sslmode=disable"+" password="+DB_PASSWORD+"")
if err != nil {
panic("failed to open storage")
}
defer db.Close()
db.AutoMigrate(&Person{})
db.Delete(Person{})
newManager := Person{
Name : "Manager 1",
}
db.Create(&newManager)
managerID := newManager.ID
newEmployee := Person{
Name : "Employee 1",
Parent : managerID,
}
db.Create(&newEmployee)
newManager = Person{
Name : "Manager 2",
}
db.Create(&newManager)
managerID = newManager.ID
newEmployee = Person{
Name : "Employee 2",
Parent : managerID,
}
db.Create(&newEmployee)
persons := []Person{}
db.Preload("Parent_").Find(&persons)
for _, person := range persons {
fmt.Println("Name :",person.Name)
if person.Parent_ != nil {
fmt.Println("Manager :",person.Parent_.Name)
}
fmt.Println("---------------------------------")
}
}
在此示例中,我希望将其作为输出:
Name : Manager 1
---------------------------------
Name : Employee 1
Manager : Manager 1
---------------------------------
Name : Manager 2
---------------------------------
Name : Employee 2
Manager : Manager 2
---------------------------------
但是我却得到了:
Name : Manager 1
Manager : Employee 1
---------------------------------
Name : Employee 1
---------------------------------
Name : Manager 2
Manager : Employee 2
---------------------------------
Name : Employee 2
---------------------------------
为什么?