You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gorm创建记录时Form-Data文件上传引发类型转换错误

问题

在PostgreSQL中通过multipart表单创建Product记录时,完成文件上传并关联File结构体后,调用gorm.Create(&product)抛出错误,注释文件关联部分则无异常。

控制器代码

func (pc ProductController) Create(c *gin.Context) {
    var product migrations.Product
    if err := c.Bind(&product); err != nil {
        c.JSON(400, gin.H{"error": err.Error(), "message": "İşlem başarısız. Lütfen tekrar deneyiniz veya sistem yöneticinize başvurun. Hata kodu: PD-CRT-01"})
        return
    }
    // 字段验证逻辑
    // 文件上传逻辑
    product.Image = &migrations.File{
        Path:      fileName,
        Extension: strings.Split(file.Filename, ".")[1],
    }
    err = db.Conn.Create(&product).Error
    if err != nil {
        c.JSON(400, gin.H{"error": err.Error(), "message": "İşlem başarısız. Lütfen tekrar deneyiniz veya sistem yöneticinize başvurun. Hata kodu: PD-CRT-04"})
        return
    }
}

错误信息

{
    "error": "strconv.ParseInt: parsing \"products\": invalid syntax; strconv.ParseInt: parsing \"products\": invalid syntax"
}

结构体关联说明

存在Order、Product、OrdersProduct、File结构体,其中Product与File通过gorm:"polymorphic:Module"建立多态关联。


解决方案

这个错误的核心是多态关联的字段类型不匹配,GORM在处理关联时尝试将字符串"products"解析为整数类型的ModuleID字段,导致转换失败。按以下步骤修复:

  1. 检查File结构体的多态字段定义
    确保ModuleID的类型与Product的主键类型一致(通常为uint或int),ModuleType为字符串类型,标签配置正确:
type File struct {
    gorm.Model
    Path      string
    Extension string
    // 与Product主键类型匹配,比如Product用uint作为ID,这里也用uint
    ModuleID   uint   `gorm:"polymorphic:Module"`
    ModuleType string `gorm:"polymorphic:Module"`
}
  1. 确认Product结构体的主键与关联配置
    Product的主键需为整数类型,关联File的标签正确:
type Product struct {
    gorm.Model // 默认包含uint类型的ID主键
    // 其他业务字段
    Image *File `gorm:"polymorphic:Module;"`
}
  1. 不要手动设置多态关联的核心字段
    创建Product时,GORM会自动将Product的ID赋值给File的ModuleID,并将ModuleType设置为对应的表名(如products),无需手动赋值,避免错误赋值触发解析异常。

  2. 优化表单绑定逻辑
    使用c.ShouldBind替代c.Bind,避免multipart表单中的冗余字段错误绑定到关联结构体的字段上:

if err := c.ShouldBind(&product); err != nil {
    // 错误处理
}

内容的提问来源于stack exchange,提问作者icsarisakal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 20:50:35