go gorm 使用问题

88 天前
 rxswift
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 用户,现在重新测试了又不会创建新用户了,这是什么原因呢

2321 次点击
所在节点    Go 编程语言
11 条回复
fffq
88 天前
fmt.Println(result.Error)
koujianshusheng
88 天前
开 debug,看执行的 sql
skiy
88 天前
GORM 有 debug_mode ,打开就知道执行语句了。
CEBBCAT
88 天前
大概率是 gorm 版本升级带来的,可以问一下 GPT 4.1
Asakijz
88 天前
不是应该 db.Create(&petInfo)嘛
billbur
88 天前
可以先查查看是不是 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
88 天前
gorm:"association_autoupdate:false;association_autocreate:false“
禁止级联更新和级联新建。不然你是外键约束,会自动创建。
rxswift
87 天前
@leonunix 之前是会自动创建,现在又不创建了,就很奇怪
SenseHu
87 天前
我们现在是 用 gorm gen, 全部自动生成
voldemort9664126
74 天前
你数据库设计的时候有联合主键或者唯一主键
rxswift
73 天前
@leonunix
@billbur
感谢,学习了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://ex.noerr.eu.org/t/1139642

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX