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

Patricia Arquette
Release: 2024-10-26 19:24:29
Original
962 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!