我有以下代码
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": ""
}
精慕HU
相关分类