Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gorm not returning ErrRecordNotFound [duplicate]

Tags:

go

go-gorm

I have the following code

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

    return true, nil
}

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?

like image 351
Rodrigo Avatar asked Jun 15 '26 15:06

Rodrigo


1 Answers

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:

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

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

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

 fmt.Println(tx.RowsAffected)
like image 143
Vusal Shahbazov Avatar answered Jun 17 '26 05:06

Vusal Shahbazov