我有以下代碼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 關注
- 111 瀏覽
添加回答
舉報
0/150
提交
取消