英文:
gorm use the find rerurn empty
问题
我使用find方法来查找一些记录,但当我发送错误的条件时,它应该返回ErrRecordNotFound,但它返回了一个空的结构体。
var projectSetBudget domain.ProjectSetBudget
filter := &domain.ProjectSetBudget{}
filter.TenantID = tenantID
filter.ID = ProjectSetBudgetID
res := r.db.Where(filter).Find(&projectSetBudget)
我只是打印了信息:
zap.S().Info(errors.Is(res.Error, gorm.ErrRecordNotFound))
它打印出false,并返回了空的结构体:
{
"ID": 0,
"CreatedAt": "0001-01-01T00:00:00Z",
"UpdatedAt": "0001-01-01T00:00:00Z",
"DeletedAt": null,
"title": ""
}
英文:
I use the find method to find some records,but when I send the wrong condition.it should return the
ErrRecordNotFound,but it return a empty struct
var projectSetBudget domain.ProjectSetBudget
filter := &domain.ProjectSetBudget{}
filter.TenantID = tenantID
filter.ID = ProjectSetBudgetID
res := r.db.Where(filter).Find(&projectSetBudget)
i just print the info
zap.S().Info(errors.Is(res.Error, gorm.ErrRecordNotFound))
it print false
and return the empty struct
{
"ID": 0,
"CreatedAt": "0001-01-01T00:00:00Z",
"UpdatedAt": "0001-01-01T00:00:00Z",
"DeletedAt": null,
"title": "",
}
答案1
得分: 2
GORM提供了First、Take、Last方法来从数据库中检索单个对象,在查询数据库时会添加LIMIT 1条件,如果未找到记录,它将返回错误ErrRecordNotFound。
https://gorm.io/docs/query.html
只有First、Take、Last方法,而find方法没有,如果使用First、Take、Last,如果找不到记录会返回ErrRecordNotFound。
First、Take、Last有以下代码,但find方法没有,find方法会查找不止一个记录,所以你可以通过计数来判断是否找到:
tx.Statement.RaiseErrorOnNotFound = true
英文:
GORM provides First, Take, Last methods to retrieve a single object from the database, it adds LIMIT 1 condition when querying the database, and it will return the error ErrRecordNotFound if no record is found.
https://gorm.io/docs/query.html
only First, Take, Last methods but find
if you use First, Take, Last there will be ErrRecordNotFound
First, Take, Last have folow code, but find have not, find will find not only one, so you can know it found or not by count:
tx.Statement.RaiseErrorOnNotFound = true
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论