Gorm没有返回ErrRecordNotFound错误。

huangapple go评论109阅读模式
英文:

Gorm not returning ErrRecordNotFound

问题

我有以下代码:

  1. func (r *WorkspaceRepository) Delete(id any) (bool, error) {
  2. if err := r.db.Where("id = ?", id).Delete(&model.Workspace{}).Error; err != nil {
  3. return false, err
  4. }
  5. return true, nil
  6. }

当我传递一个不存在的ID时,没有返回错误,就好像记录存在一样!

在删除之前,我需要做什么检查?我需要先执行一个SELECT吗?

英文:

I have the following code

  1. func (r *WorkspaceRepository) Delete(id any) (bool, error) {
  2. if err := r.db.Where("id = ?", id).Delete(&model.Workspace{}).Error; err != nil {
  3. return false, err
  4. }
  5. return true, nil
  6. }

When I pass an ID that does not exist, no errors are returned, as if the record existed!

What do I need to do to check before deleting, do I need to do a SELECT first?

答案1

得分: 7

删除方法不会返回ErrRecordNotFound错误。文档在这里:https://gorm.io/docs/error_handling.html

GORM在使用First、Last、Take方法无法找到数据时会返回ErrRecordNotFound错误

代码:

  1. r.db.Where("id = ?", id).Delete(&model.Workspace{})

返回gorm.DB结构体,你可以检查是否删除了任何项

  1. tx := r.db.Where("id = ?", id).Delete(&model.Workspace{})
  2. fmt.Println(tx.RowsAffected)
英文:

Delete method does not return ErrRecordNotFound error. Docs here: https://gorm.io/docs/error_handling.html

GORM returns ErrRecordNotFound when failed to find data with First, Last, Take

Code:

  1. r.db.Where("id = ?", id).Delete(&model.Workspace{})

return gorm.DB struct and you can check if any item deleted or not

  1. tx := r.db.Where("id = ?", id).Delete(&model.Workspace{})
  2. fmt.Println(tx.RowsAffected)

huangapple
  • 本文由 发表于 2022年7月5日 03:56:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/72861473.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定