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
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.