首頁  >  文章  >  後端開發  >  GORM 中的外鍵未更新

GORM 中的外鍵未更新

WBOY
WBOY轉載
2024-02-09 11:57:071051瀏覽

GORM 中的外键未更新

最近在使用GORM時,我發現一個問題-外鍵未更新的情況。當我在關聯的表中更新了外鍵欄位的值時,卻沒有同步更新到另一張表中。透過調查和研究,我發現這是因為GORM預設不會自動更新外鍵欄位。這個問題困擾了我一段時間,所以我決定將解決方法分享給大家。在本文中,我將向大家介紹如何使用GORM來正確更新外鍵字段,以避免這個問題。

問題內容

我有兩張桌子,一張是公司

type Company struct {
    Id        uuid.UUID `gorm:"column:id;primaryKey;"`
    CreatedAt time.Time `gorm:"index;column:createdAt"`
    UpdatedAt time.Time `gorm:"index;column:updatedAt"`
    Name      string    `gorm:"column:name" binding:"required"`
}

另一個是product_entitlement

type ProductEntitlement struct {
ID        uuid.UUID
CreatedAt time.Time `gorm:"index;column:createdAt"`
UpdatedAt time.Time `gorm:"index;column:updatedAt"`
Type       string    `gorm:"column:type" binding:"required"`
CompanyID  uuid.UUID `gorm:"column:companyId;size:36"`
Company    Company   `gorm:"foreignKey:CompanyID"`
}

CompanyID 是外鍵。 CompanyID 包含來自 Company.Id 的值

更新插入完成後,每次都會插入新行。這是我們正在使用的程式碼

func UpdateEntitlement(c *gin.Context) {
cid := c.Param("companyId")
    id := c.Param("entitlementId")
    eid := uuid.MustParse(id)
    log.Println(eid)
    uid := uuid.MustParse(cid)
    log.Println(uid)
    var entitlementRequest entities.ProductEntitlement
    if err := c.BindJSON(&entitlementRequest); err != nil {
        log.Println(err)
        fmt.Println("ERROR: ", err)
        c.JSON(400, gin.H{"error": "Invalid JSON format"})
        return
    }
    if err := database.DB.Clauses(clause.OnConflict{
        Columns:   []clause.Column{{Name: "id"}},
        UpdateAll: true,
    }).Create(&entitlementRequest).Error; err != nil {
        log.Println(err)
    }
}

但它總是失敗並給出錯誤

BD820BD3F94A2A45E18ED8E8094EF395

如果 ID 存在,我想更新 Product_entitlement,否則建立一個新的

網址如下, http://localhost:8080/company/{{companyId}}/product/{{companyId}} 並使用 PUT 方法 身體是

{「類型」:「自動」}

解決方法

如果它對某人有幫助,我們可以使用FirstOrCreate 函數來檢查id 是否存在並進行更新,如果不存在則建立一個新的。

要指派外鍵,我們需要將值指派給相關表,

entitlementRequest.CompanyID = uid

#
func UpdateEntitlement(c *gin.Context) {
    cid := c.Param("companyId")
    uid := uuid.MustParse(cid)
    eid := c.Param("entitlementId")
    nid := uuid.MustParse(eid)
    var entitlementRequest entities.ProductEntitlement
    entitlementRequest.CompanyID = uid

    if err := c.BindJSON(&entitlementRequest); err != nil {
        fmt.Println("ERROR: ", err)
        c.JSON(400, gin.H{"error": "Invalid JSON format"})
        return
    }
    if err := database.DB.Where("id = ?", nid).
        Assign(entitlementRequest).
        FirstOrCreate(&entitlementRequest).Error; err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
        return
    }
    c.JSON(http.StatusOK, gin.H{"error": "Product entitlement upserted successfully"})
}

以上是GORM 中的外鍵未更新的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除