ラベル gorm の投稿を表示しています。 すべての投稿を表示
ラベル gorm の投稿を表示しています。 すべての投稿を表示

2024/03/03

2019/12/18

golang gorm update when record not exist

when record is not exist. update will be success.
have to check RowsAffected .
the same as delte

query := db.Model(r).Updates(something)
if query.Error != nil {
   return query.Error
}
if query.RowsAffected == 0 {
   return gorm.ErrRecordNotFound
}



query := db.Delete(&something{ID: ID})
if query.Error != nil {
   return query.Error
}
if query.RowsAffected == 0 {
   return gorm.ErrRecordNotFound
}

2018/10/19

gorm transaction

TransactionsTo perform a set of operations within a transaction, the general flow is as below.
// begin a transaction
tx := db.Begin()

// do some database operations in the transaction (use 'tx' from this point, not 'db')
tx.Create(...)

// ...

// rollback the transaction in case of error
tx.Rollback()

// Or commit the transaction
tx.Commit()