创建数据库记录时如何加载预加载关联?

How do I load preload associations when creating a database record?

我有以下代码

func Employees(db *database.Database) fiber.Handler {
    return func(c *fiber.Ctx) error {

        var employees []model.Employee

        if response := db.Preload(clause.Associations).Find(&employees); response.Error != nil {
            return c.JSON(responseKit.RecordNotFoundError())
        }

        return c.JSON(responseKit.RecordsFoundSuccess(employees, len(employees)))
    }
}

func CreateEmployee(db *database.Database) fiber.Handler {
    return func(c *fiber.Ctx) error {
        employee := new(model.Employee)

        if err := c.BodyParser(employee); err != nil {
            fmt.Printf("%v", err)
            return c.JSON(responseKit.ParsingError())
        }

        // if err := employee.Validate(); err != nil {
        //  return c.JSON(responseKit.ValidationError(err))
        // }

        if result := db.Preload(clause.Associations).Omit(clause.Associations).Create(&employee); result.Error != nil {
            return c.JSON(responseKit.RecordCreateError())
        }

        return c.JSON(responseKit.RecordCreateSuccess(employee))
    }
}

我在寻找员工时预先加载所有关联。这按预期工作,我让员工预加载了他们的关联。响应中的关联看起来像这样 json

    "groupID": 1,
    "group": {
        "id": 1,
        "title": "Test"
    },
    "roleID": 1,
    "role": {
        "id": 1,
        "title": "Test"
    }

但是当我创建员工时预加载不起作用。所以我得到的响应没有组或角色数据只有 ID

"groupID": 1,
"group": {
    "id": 0,
    "title": ""
},
"roleID": 1,
"role": {
    "id": 0,
    "title": ""
}

这是我的员工模型

type Employee struct {
    PrivateGormModel
    Person      `gorm:"embedded" json:"person,omitempty"`
    Contact     `gorm:"embedded" json:"contact,omitempty"`
    Address     `gorm:"embedded" json:"address,omitempty"`
    AltContact  `gorm:"embedded" json:"privateContact,omitempty"`
    BankAccount `gorm:"embedded" json:"bankAccount,omitempty"`
    GroupID     uint          `json:"groupID"`
    Group       EmployeeGroup `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;" json:"group"`
    RoleID      uint          `json:"roleID"`
    Role        EmployeeRole  `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;" json:"role"`
}

创建条目时如何预加载数据?在本例中,组和角色在数据库中已有条目,因此我创建了一个带有指向该角色和组的 ID 的员工条目。我使用以下 json

{
    "person":{
        "initials":"",
        "firstName":"",
        "middleName":"",
        "lastName":"",
        "dateOfBirth":"",
        "language":""
    },
    "address":{
        "country":"",
        "zip":"",
        "number":"0",
        "addition":"",
        "street":"",
        "state":"",
        "city":""
    },
    "contact":{
        "tel":"",
        "mail":"",
        "url":""
    },
    "bankAccount":{
        "bank":"",
        "bic":"",
        "iban":"",
        "accountHolder":"",
        "establishment":""
    },
    "roleID":1,
    "groupID":1
}

它不起作用,因为您在 CreateEmployee 函数中省略了 clause.Associations

  • 现有代码段\/
if result := db.Preload(clause.Associations).Omit(clause.Associations).Create(&employee); result.Error != nil {
            return c.JSON(responseKit.RecordCreateError())
        }
  • 新片段\/
if result := db.Preload(clause.Associations).Create(&employee); result.Error != nil {
            return c.JSON(responseKit.RecordCreateError())
        }
  • 编辑
if result := db.Preload(clause.Associations).Find(&employee); result.Error != nil {
            return c.JSON(responseKit.RecordCreateError())
        }