亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

創建數據庫記錄時如何加載預加載關聯?

創建數據庫記錄時如何加載預加載關聯?

Go
jeck貓 2022-08-01 15:01:46
我有以下代碼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())

        }


查看完整回答
反對 回復 2022-08-01
  • 1 回答
  • 0 關注
  • 111 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號