How to Handle Non-Existent Rows in GORM\'s Delete Function?

Mary-Kate Olsen
Release: 2024-10-27 10:26:30
Original
992 people have browsed it

How to Handle Non-Existent Rows in GORM's Delete Function?

Handling Errors in GORM's Delete Function

When working with database deletions using GORM, it's crucial to consider how you want to handle non-existent rows. By default, GORM does not throw an error when trying to delete a non-existent row. Instead, the result.Error field remains nil.

To alter this behavior and return an error for non-existent rows, you need to inspect the RowsAffected field. Here's how you can modify your DeleteCategory function:

<code class="go">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

In this modified function:

  1. GORM's Delete method is invoked, assigning the result to db.
  2. If db.Error is not nil, an error is returned.
  3. After confirming that there is no general error, db.RowsAffected is checked. If it is less than 1, indicating that no rows were affected by the delete operation, a custom error message is returned.
  4. A nil error value is returned if the row deletion was successful.

The above is the detailed content of How to Handle Non-Existent 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!