Creating or Updating Records with GORM: FirstOrCreate vs. Upsert
GORM provides two methods for creating or updating records: FirstOrCreate and FirstOrInit. However, it can be challenging to determine if a record was actually created using these methods.
Upsert Support in GORM 1.20.x and Above
Since version 1.20.x, GORM introduces a compatible Upsert support through the OnConflict clause. This allows for upserting records on different databases.
// Update columns on conflict DB.Clauses(clause.OnConflict{ Columns: []clause.Column{{Name: "id"}}, DoUpdates: clause.AssignmentColumns([]string{"name", "age"}), }).Create(&users)
Alternative Approach for GORM 1.9.x and Below
In earlier versions of GORM, an efficient method to create or update records is by first attempting an update, followed by an insert if the record does not exist.
if err := db.Model(&newUser).Where("id = ?", 3333).Update("name", "nick").Error; err != nil { if gorm.IsRecordNotFoundError(err) { db.Create(&newUser) } }
Distinction between FirstOrInit and FirstOrCreate
It's important to note the distinction between FirstOrInit and FirstOrCreate. While both methods return a pointer to an existing or a newly created record, FirstOrInit only initializes the struct without creating a record, whereas FirstOrCreate creates a record and queries it into the struct.
The above is the detailed content of FirstOrCreate vs. Upsert: Which GORM method should you use for creating or updating records?. For more information, please follow other related articles on the PHP Chinese website!