我有以下代码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": ""}
1 回答
精慕HU
TA贡献1845条经验 获得超8个赞
它不起作用,因为您在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())
}
- 1 回答
- 0 关注
- 95 浏览
添加回答
举报
0/150
提交
取消