GORM 中的外键未更新

问题描述 投票:0回答:1

我有两张桌子,一张是公司的

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)
    }
}

但它总是失败并给出错误为

 Error 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`crud_demo`.`product_entitlement`, CONSTRAINT `fk_company_product_entitlements` FOREIGN KEY (`companyId`) REFERENCES `company` (`id`))

如果 id 存在,我想更新 Product_entitlement,否则创建一个新的

网址如下, http://localhost:8080/company/{{companyId}}/product/{{companyId}} 并使用 PUT 方法 身体是

{“类型”:“自动”}

go foreign-keys go-gorm
1个回答
0
投票

如果它对某人有帮助,我们可以使用

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"})
}
© www.soinside.com 2019 - 2024. All rights reserved.