英文:
Gorm not returning ErrRecordNotFound
问题
我有以下代码:
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
}
当我传递一个不存在的ID时,没有返回错误,就好像记录存在一样!
在删除之前,我需要做什么检查?我需要先执行一个SELECT吗?
英文:
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?
答案1
得分: 7
删除方法不会返回ErrRecordNotFound错误。文档在这里:https://gorm.io/docs/error_handling.html
GORM在使用First、Last、Take方法无法找到数据时会返回ErrRecordNotFound错误
代码:
r.db.Where("id = ?", id).Delete(&model.Workspace{})
返回gorm.DB结构体,你可以检查是否删除了任何项
tx := r.db.Where("id = ?", id).Delete(&model.Workspace{})
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:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论