V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
rxswift
V2EX  ›  Go 编程语言

go gorm 使用问题

  •  1
     
  •   rxswift · 74 天前 · 2276 次点击
    这是一个创建于 74 天前的主题,其中的信息可能已经有所发展或是发生改变。
    type PetInfo struct {
    	BaseModel
    	User     UserInfo json:"user" form:"user"
    	UserId   uint     json:"userId" form:"userId"
    	PetType  string   json:"petType" form:"petType" gorm:"size:64"
    	Avatar   string   json:"avatar" form:"avatar" gorm:"size:64" binding:"required"
    	Name     string   json:"name" form:"name" gorm:"size:32" binding:"required"
    }
    func PetInfoCreate(c *gin.Context) {
    	userId := c.MustGet("userId").(uint)
    	var petInfo = models.PetInfo{}
    	if err := c.ShouldBind(&petInfo); err != nil {
    		response.Fail(c, response.ApiCode.ParamErr, response.ApiMsg.ParamErr)
    		return
    	}
    	// 忽略 User 是因为 ShouldBind 会创建一个 User 默认值,导致插入一条新的用户数据
        // result := db.DB.Omit("User").Create(&petInfo)
    	result := db.DB.Create(&petInfo)
    	if result.Error != nil {
    		response.Fail(c, response.ApiCode.CreateErr, response.ApiMsg.CreateErr)
    		return
    	}
    	response.Success(c, nil)
    }
    

    去年在使用 gorm 的时候在我写这段代码时:result := db.DB.Create(&petInfo),传教 petInfo 时会同时创建一个新的 User 用户,现在重新测试了又不会创建新用户了,这是什么原因呢

    11 条回复    2025-07-04 09:56:27 +08:00
    fffq
        1
    fffq  
       74 天前
    fmt.Println(result.Error)
    koujianshusheng
        2
    koujianshusheng  
       74 天前
    开 debug,看执行的 sql
    skiy
        3
    skiy  
       74 天前
    GORM 有 debug_mode ,打开就知道执行语句了。
    CEBBCAT
        4
    CEBBCAT  
       74 天前
    大概率是 gorm 版本升级带来的,可以问一下 GPT 4.1
    Asakijz
        5
    Asakijz  
       74 天前
    不是应该 db.Create(&petInfo)嘛
    billbur
        6
    billbur  
       74 天前
    可以先查查看是不是 db 被其他哪个地方修改了
    https://gorm.io/zh_CN/docs/create.html#%E5%85%B3%E8%81%94%E5%88%9B%E5%BB%BA

    // skip all associations
    db.Omit(clause.Associations).Create(&user)
    leonunix
        7
    leonunix  
       74 天前
    gorm:"association_autoupdate:false;association_autocreate:false“
    禁止级联更新和级联新建。不然你是外键约束,会自动创建。
    rxswift
        8
    rxswift  
    OP
       74 天前
    @leonunix 之前是会自动创建,现在又不创建了,就很奇怪
    SenseHu
        9
    SenseHu  
       73 天前
    我们现在是 用 gorm gen, 全部自动生成
    voldemort9664126
        10
    voldemort9664126  
       60 天前
    你数据库设计的时候有联合主键或者唯一主键
    rxswift
        11
    rxswift  
    OP
       59 天前
    @leonunix
    @billbur
    感谢,学习了
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3863 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 10:21 · PVG 18:21 · LAX 03:21 · JFK 06:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.