首页  >  文章  >  后端开发  >  如何处理 GORM 的删除功能中不存在的行?

如何处理 GORM 的删除功能中不存在的行?

Patricia Arquette
Patricia Arquette原创
2024-10-26 19:24:29946浏览

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

避免 GORM 删除函数中的零错误

在 GORM 应用程序中,尝试删除不存在的行不会被识别为错误。为了确保正确的错误处理,必须检查受影响的行数。

考虑以下 DeleteCategory 函数:

<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>

使用相同的 id 多次调用此函数不会产生错误,尽管第一次只删除一行。这是因为 SQL 标准不认为删除不存在的行是错误。

要纠正此问题,请添加对 RowsAffected 字段的检查:

<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>

通过此修改,函数将返回如果指定 id 的行不存在,则会出错。

以上是如何处理 GORM 的删除功能中不存在的行?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn