自引用结构,带有预加载父母的记录在父母和孩子之间切换

时间:2019-04-08 17:21:39

标签: go go-gorm

我有一个自引用的结构,当我尝试使用Preload来获取数据时,记录会以某种方式在父级和子级之间切换。

在此示例中,我创建了以下记录:

  1. 一个叫经理1的人
  2. 一个叫雇员1的人 经理1作为其父母
  3. 一个叫经理2的人
  4. 一个人叫 以经理2为父母的员工2

代码如下:

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
---------------------------------

为什么?

0 个答案:

没有答案