How to Create or Update a record with GORM?

前端 未结 7 1389
悲&欢浪女
悲&欢浪女 2021-01-05 04:21

Gorm has a FirstOrCreate method and a FirstOrInit but how to check afterwards if the record was actually created? I like to create a record if it d

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-05 04:50

    The most upvoted answer did not work for me, but this did:

    user := NewUser(email, password)
    if db.Model(&user).Where("email = ?", email).Updates(&user).RowsAffected == 0 {
        db.Create(&user)
    }
    

    This works for gorm v1.9.15 and go 1.13

提交回复
热议问题