How to Create or Update a record with GORM?

前端 未结 7 1392
悲&欢浪女
悲&欢浪女 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:46

    There is a better way to do it:

        if err := db.Where(User{Email: "some@email.com"}).
           Assign(User{Email: "some@email.com", Age: 45}).
           FirstOrCreate(&User{}).Error; err != nil {
             c.Next(err)
             return
        }
    

    In this example, if a user with email "some@email.com" is found, then the field "Age" will be updated. On the contrary, if no user if found, then it is created.

    Note that I am discarding the created user, but you can keep the reference if you want. Also, for some GORM reasons, it is required to provide at least a filter field in the Assign clause, that's why you see email being populated twice.

提交回复
热议问题