Home  >  Article  >  Backend Development  >  How to Handle Nonexistent Rows in GORM\'s Delete Function?

How to Handle Nonexistent Rows in GORM\'s Delete Function?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 19:24:29946browse

How to Handle Nonexistent Rows in GORM's Delete Function?

Avoiding Nil Errors in GORM's Delete Function

In a GORM application, attempting to delete a nonexistent row is not recognized as an error. To ensure proper error handling, it's essential to inspect the number of affected rows instead.

Consider the following DeleteCategory function:

<code class="golang">var db *gorm.DB

func DeleteCategory(id uint) error {
    var category Category
    category.ID = id
    result := db.Delete(&category)
    fmt.Println("result.Error: ", result.Error)
    return result.Error
}</code>

Calling this function multiple times with the same id does not produce an error, despite deleting only one row the first time. This is because the SQL standard does not consider deleting nonexistent rows an error.

To rectify this, add a check for the RowsAffected field:

<code class="golang">func DeleteCategory(id uint) error {
    c := Category{ID: id}

    db := db.Delete(&c)
    if db.Error != nil {
        return db.Error
    } else if db.RowsAffected < 1 {
        return fmt.Errorf("row with id=%d cannot be deleted because it doesn't exist", id)
    }

    return nil
}</code>

With this modification, the function will return an error if the row with the specified id does not exist.

The above is the detailed content of How to Handle Nonexistent Rows in GORM\'s Delete Function?. 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