Home >Backend Development >Golang >FirstOrCreate vs. Upsert: Which GORM method should you use for creating or updating records?

FirstOrCreate vs. Upsert: Which GORM method should you use for creating or updating records?

Linda Hamilton
Linda HamiltonOriginal
2024-11-09 16:20:02387browse

FirstOrCreate vs. Upsert: Which GORM method should you use for creating or updating records?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn